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



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

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

到目前为止,我对正则表达式缺乏了解正在杀死我。 我开始做这样的事情...但是这个方向是行不通的:

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

注意:字符串可以四处移动。 我想说如果一个(如果你看到,通过添加*来显示开始孩子)关闭孩子。 我认为这可能更像是一堆 ifs 哈哈的循环。

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

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--;
    }
});

您可以使用一种独特的替换方法:

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);

我不确定为什么您希望将其作为多行字符串而不是 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);

最新更新