slevithan / xregexp

Extended JavaScript regular expressions
http://xregexp.com/
MIT License
3.31k stars 278 forks source link

Recursive doesn't work as expected #272

Closed RezaRahmati closed 5 years ago

RezaRahmati commented 5 years ago

I have below code

const XRegExp = require('xregexp');

const str2 = `messages: {something:'val', x: { y } }`;

const arr2 = XRegExp.matchRecursive(str2, 'messages: {', '}', 'gi');

console.log(arr2);

const str = `{ prop1: 'val1', prop2:{ prop3: 'val3' , messages: {something:'val'} messages: { something:'val2', x : {x : 1, y : 5} } prop4 : 'val4' } }`;

const arr = XRegExp.matchRecursive(str, 'messages: {', '}', 'gi');

console.log(arr);

for both I receive Error: Unbalanced delimiter found in string at Function.XRegExp.matchRecursive

I expect to find all messages: { ... }

Please take a look at https://repl.it/@RezaRahmati/xregexp

slevithan commented 5 years ago

The issue is that, to use your first example subject string, there is only one opening delimiter in the string (“messages: {“) and two closing delimiters (“}”). Although I would definitely like to update XRegExp.matchRecursive to provide an option to support subject strings with non-balanced delimiters, that just hasn’t been built yet (see #96 for details).

Changing the opening delimiter to “messages: {|{“ should fix this and work as you expect. You could then check your matches to see whether they start with “messages: {“ or just “{“, and discard the latter.