简体   繁体   中英

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

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

Make use of global match flag . Also using a negative lookahead would ensure that you are not missing any matches or not hitting any false matches.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM