Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match a string pattern multiple times in the same line

I want to find a specific pattern inside a string.

The pattern: (\{\$.+\$\})
Example matche: {$ test $}

The problem I have is when 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 returns 2 matches: {$ test $} and {$ another test $}

Note: I'm using Javascript

like image 367
User1 Avatar asked Jan 24 '15 14:01

User1


1 Answers

Problem is that your regex (\{\$.+\$\}) is greedy in nature when you use .+ that's why it matches longest match between {$ and }$.

To fix the problem make your regex non-greedy:

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

Or even better use negation regex:

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

RegEx Demo

like image 168
anubhava Avatar answered Nov 10 '22 12:11

anubhava