[英]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 $}
示例matche:
{$ test $}
The problem I have is when the text has 2 matches on the same line. 我遇到的问题是文本在同一行上有2个匹配项。 It returns one match.
它返回一个匹配。 Example:
this is a {$ test $} content {$ another test $}
示例:
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
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: 或者甚至更好地使用否定正则表达式:
(\{\$[^$]+\$\})
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.