正则表达式或For循环字符串 - 拆分和连接

时间:2017-01-11 16:26:09

标签: javascript regex string for-loop

我正在尝试拼凑一个RegEx,它将使用此格式(person,item(bought,paid),shipping(address(city,state)))的字符串并将其转换为格式如下的字符串:

person
item
* bought
* paid
shipping
* address
** city
** state

到目前为止,我缺乏理解RegEx正在杀死我。我开始做这样的事情......但是这个方向不起作用:

var stg = "(person,item(bought,paid),shipping(address(city,state)))"
var separators = [' ', '\"\\\(', '\\\)\"', ','];
  stg = stg.split(new RegExp(separators.join('|'), 'g'));

注意:字符串可以移动。我试图说一个(如果你看到的话,通过添加*来显示开始孩子)关闭孩子。我认为这可能更多是在一个带有一堆ifs的for循环中。

3 个答案:

答案 0 :(得分:4)

您可以编写自己的迭代器:



str = '(person,item(bought,paid),shipping(address(city,state)))';
counter = -1;
// Split and iterate
str.split(/([(,)])/).filter(Boolean).forEach(function(element) {
    if (element.match(/^[^(,)]/)) {
    	console.log("*".repeat(counter) + ((counter > 0) ? ' ' : '') + element)
    } else if (element == '(') {
    	counter++;
    } else if (element == ')') {
    	counter--;
    }
});




答案 1 :(得分:1)

您可以使用一种独特的替换方法来执行此操作:

str='person,item(bought,paid),shipping(address(city,state))';

var asterisks = '';
var result = str.replace(/(\()|(\))|,/g, (match, openP, closingP) => {
    if (openP) {
        return '\n' + (asterisks += '*');
    }
    if (closingP) {
        asterisks = asterisks.slice(1);
        return '';
    }
    // else: is comma
    return '\n' + asterisks;
});

console.log(result);

答案 2 :(得分:0)

我不确定你为什么要将它作为多行字符串而不是JSON ... 但是你走了:

var regex = /\((.*?)\,(.*?)\((.*?),(.*?)\),(.*?)\((.*?)\((.*?),(.*?)\)\)\)/;
var string = '(person,item(bought,paid),shipping(address(city,state)))';

var matches = string.match(regex)

var resultString = matches[1] + "\n";
resultString += matches[2] + "\n" ;
resultString += "* " + matches[3] + "\n" ;
resultString += "* " + matches[4] + "\n" ;
resultString += matches[5] + "\n" ;
resultString += "* " + matches[6] + "\n" ;
resultString += "** " + matches[7] + "\n" ;
resultString += "** " + matches[8];

console.log(resultString);
相关问题