正则表达式/ g - 全局搜索标志不将结束标记计为下一个起始标记

时间:2014-07-12 07:40:11

标签: javascript regex

我有一行文字,如:

    Hi %this% is the %text% I was talking about.

我想用其他文字替换%this%%text%。我正在使用这个正则表达式:

str.replace(/(%)(.*)(%)/g, "something")

但这取代了三个字符串%this%%text%以及% is the %。是否有任何标记让/g%结束标记后重新开始,而不将其计为下一个起始标记?

3 个答案:

答案 0 :(得分:2)

问题是.*在你的正则表达式中过于贪婪。

你可以使用否定:

var r = str.replace(/%[^%]*%/g, "something");
//=> Hi something is the something I was talking about

或者只是匹配%

之间的单词
var r = str.replace(/%\w*%/g, "something");

答案 1 :(得分:1)

你可以试试下面的正则表达式,

> '    Hi %this% is the %text% I was talking about.'.replace(/%.*?%/g, "something")
'    Hi something is the something I was talking about.'

<强>解释

  • %匹配文字%
  • .*?%匹配下一个%?迫使正则表达式引擎进行最短匹配后*

答案 2 :(得分:0)

怎么样

str.replace(/%[^%]*%/g, "something")