How to find all instances of a pattern with regex or regexp in javascript

432 views Asked by At

I have this string

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

how can I find all instances of messages: { ... } in javascript with xregexp (or another solution)

This /messages: (\{(?>[^{}]+|(?1))*\})/g is working in php, but not in javascript

enter image description here

Also couldn't figure it out by using xregexp recursion http://xregexp.com/api/#matchRecursive

Tried https://repl.it/@RezaRahmati/xregexp

XRegExp.matchRecursive(str, 'messages: {', '}', 'gi')

but getting Unbalanced delimiter found in string error

Update

as @vs97 and @barmar comment, I tried messages: (\{.+\}) and works on multiline, still issue when it's single line

enter image description here

1

There are 1 answers

11
Barmar On

Unfortunately, matchBalanced() is not useful for this, because of this:

An error is thrown if delimiters are unbalanced within the data.

So you can't use it just to find the balanced parts of the string, you can only use it with data that's expected to be balanced -- it returns the outermost substrings. Since what you're looking for are the balanced parts that are nested inside, it won't return them.