Match a line pattern multiple times on the same line

I want to find a specific pattern inside a string.

Sample: (\{\$.+\$\})
Matche example:{$ test $}

The problem is that the text has 2 matches on the same line. It returns one match. Example:this is a {$ test $} content {$ another test $}

This returns 1 match: {$ test $} content {$ another test $}

It should return 2 matches: {$ test $}and{$ another test $}

Note. I am using javascript

+4
source share
2 answers

The problem is that your regular expression (\{\$.+\$\})is greedy in nature when you use it .+, so it matches the longest match between {$and }$.

To fix the problem, make your regular expression inanimate:

(\{\$.+?\$\})

:

(\{\$[^$]+\$\})

- RegEx

+10

. , .

var s = "this is a {$ test $} content {$ another test $}";
var reg = /\{\$.*?(?!\{\$.*\$\}).*?\$\}/g;
console.log(s.match(reg));
0

All Articles