2017-01-11 37 views
2

我試圖拼湊出一個正則表達式,將採取一個字符串,這個格式(person,item(bought,paid),shipping(address(city,state)))並把它變成格式化像這樣的字符串:正則表達式或For循環的字符串 - 斯普利特和加入

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循環。

+0

您的問題還不清楚。你想把它格式化爲多行字符串,並在其中插入'*'字符?或者是一串字符串? – Yathi

+0

@Yathi首選多行字符串,加*標記兒童。注意雙**來標記孩子的孩子。 – RooksStrife

回答

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(/^[^(,)]/)) { 
 
    \t console.log("*".repeat(counter) + ((counter > 0) ? ' ' : '') + element) 
 
    } else if (element == '(') { 
 
    \t counter++; 
 
    } else if (element == ')') { 
 
    \t counter--; 
 
    } 
 
});

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

有沒有辦法做到這一點,而不依賴於比賽?就像字符串移動一樣。那麼更多注意到(開始一個孩子並且)關閉? – RooksStrife

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