在同一行中多次匹配字符串模式

时间:2022-12-05 10:04:49

I want to find a specific pattern inside a string.

我想在字符串中找到一个特定的模式。

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

模式:(\ {\ $。+ \ $ \})示例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 $}

我遇到的问题是文本在同一行上有2个匹配项。它返回一个匹配。示例:这是{$ test $}内容{$ another test $}

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

这将返回1个匹配:{$ test $}内容{$ another test $}

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

它应该返回2个匹配:{$ test $}和{$ another test $}

Note: I'm using Javascript

注意:我正在使用Javascript

2 个解决方案

#1


10  

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

#2


0  

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));

#1


10  

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

#2


0  

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));