[英]Match a string pattern multiple times in the same line
我想在字符串中找到一个特定的模式。
模式: (\\{\\$.+\\$\\})
示例matche: {$ test $}
我遇到的问题是文本在同一行上有2个匹配项。 它返回一个匹配。 示例: this is a {$ test $} content {$ another test $}
这将返回1个匹配: {$ test $} content {$ another test $}
它应该返回2个匹配: {$ test $}
和{$ another test $}
注意:我正在使用Javascript
问题是当你使用时,你的正则表达式(\\{\\$.+\\$\\})
本质上是贪婪的.+
这就是为什么它匹配{$
和}$
之间的最长匹配。
要解决这个问题,请使你的正则表达式不贪婪:
(\{\$.+?\$\})
或者甚至更好地使用否定正则表达式:
(\{\$[^$]+\$\})
利用全局匹配标志 。 同样使用否定前瞻将确保您没有遗漏任何匹配或没有击中任何错误匹配。
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.