there is a set specified by the user, it needs to be divided into elements using regular cuttings. example: {a}, b, {a, c, b}, {a, {a, b}} - set
{a}; b; {a, c, b}, {a, {a, b}} - set into elements
|
1 answer
JavaScript does not support recursion in regular expressions, so the task cannot be solved solely by regular expressions.
The solution with the nesting counter is very elegant indeed:
var repl = (function(m, m1){ if (typeof(m1)!=="undefined") this.count=0; if (m=="{") this.count++; else if (m=="}") this.count--; else if (m=="," && this.count==0) return "\n"; return m ; }).bind({count:0}) var result = "{a},b,{a,c,b},{a,{a,b}}".replace( /(^.)|[{},]/g, repl ) Result (separated by line breaks):
{a} b {a,c,b} {a,{a,b}} Principle of operation:
- Everything happens in a function that triggers on every match with a regular expression.
- If we are at the beginning of the line, then reset the counter
- Having met the opening bracket we increase the counter
- Having met closing bracket - we reduce the counter
- Having met a comma at the counter equal to zero - we make actions for preservation of result. In this case, the comma is replaced with a line break
Processing the wrong grammar at the entrance is not provided - not included in the scope of the question.
|
([{]+[{,\w]*[}]+), but it does not fail for{},x,{{{y}}},{x,{y,z},a}- Alexey Sevko