i have to extract parts of a string, actually splitting it where there are spaces. But because there might also be spaces inside the parts i want to extract, i came upon a regex for them to be ignored, actually when those spaces are between brackets. Note that i don't fully understand the alternatives in regex, made a lot of tests, and i manage it with one bracket level (first log in the example). Also brackets might not be there, so i came upon the last alternative (|[^\s]+
) to get things like tag1
too.
After a lot of (not working) tests, i came upon the second regexp, which consists in the first alternative from the first regexp, modified to recognize the second level of nesting, followed the whole first regexp as a second alternative.
This is working fine (so far as there is not a third nesting level, see the example), but i have a feeling there should be an easier solution, as the pattern seems to be recursive (new nesting level + whole last level regexp).
Is there a way to solve this in a more general way (maybe not infinite nesting level, but let's say 4 or 5 deep?). Maybe with recursive regexp?
var str = "tag1 tag2 func(foo) func2(foo, bar) func1(func2(foo), bar, func2(bar)) func1(func2(foo, func1(foo)), bar)";
console.log( str.match(/([^\s]*\([^()]+\)[^\s]*|[^\s]+)/g) );
console.log( str.match(/([^\s]*\((?:[^()]*\([^()]+\)[^()]*)+\)[^\s]*|(?:[^\s]*\([^()]+\)[^\s]*|[^\s]+))/g) );
Edit: I'm not picky about being tagged as duplicate, but note that i searched a lot about this problem (match a pattern, excluding when the pattern is between certain chars, at an finite nesting level). My question is specific to that, recursive regex was only a suggestion to solve it, not the main part. Actually the topic tagged as duplicate does not help me in any way..