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

  • Um ... It won't work. - Qwertiy
  • Why? For example, for this option there is such a solution ([{]+[{,\w]*[}]+) , but it does not fail for {},x,{{{y}}},{x,{y,z},a} - Alexey Sevko
  • That is why. Regular expressions are not able to bracket sequences. - Qwertiy
  • And in general, and what did not please the normal option? - Qwertiy
  • What, for example? - Alexey Sevko Nov.

1 answer 1

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:

  1. Everything happens in a function that triggers on every match with a regular expression.
  2. If we are at the beginning of the line, then reset the counter
  3. Having met the opening bracket we increase the counter
  4. Having met closing bracket - we reduce the counter
  5. 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.