javascript 在同一行中多次匹配字符串模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28126797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Match a string pattern multiple times in the same line
提问by User1
I want to find a specific pattern inside a string.
我想在字符串中找到特定的模式。
The pattern: (\{\$.+\$\})
Example matche: {$ test $}
模式:(\{\$.+\$\})
示例匹配:{$ 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 个匹配项。它返回一场比赛。例子:this is a {$ test $} content {$ another test $}
This returns 1 match: {$ test $} content {$ another test $}
这将返回 1 个匹配项: {$ test $} content {$ another test $}
It should returns 2 matches:
{$ test $}
and {$ another test $}
它应该返回 2 个匹配项:
{$ test $}
和{$ another test $}
Note: I'm using Javascript
注意:我正在使用 Javascript
回答by anubhava
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
正则表达式演示
回答by Ozan
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));