Javascript RegExp-mask问题

时间:2010-04-02 07:20:25

标签: javascript regex

我有一个看起来像这样的字符串:

{theField} > YEAR (today, -3) || {theField}  < YEAR (today, +3)

我希望将其替换为:

{theField} > " + YEAR (today, -3) + " || {theField}  < " + YEAR (today, +3) + "

我试过这个:

String.replace(/(.*)(YEAR|MONTH|WEEK|DAY+)(.*[)]+)/g, "$1 \" + $2 $3 + \"")

但这给了我:

{theField} > YEAR (today, +3) || {theField}  >  " + YEAR  (today, +3) + "

有没有人有任何想法?

1 个答案:

答案 0 :(得分:1)

当你.*时,你应该小心使用贪婪的匹配。通常这不会做你想要的 - 它尽可能多地匹配字符串。您需要使用否定字符类才能在达到某个字符时停止匹配(例如[^)]),或者使用lazy匹配.*?。以下是使用惰性量词的方法:

s = '{theField} > YEAR (today, -3) || {theField}  < YEAR (today, +3)';
result = s.replace(/((YEAR|MONTH|WEEK|DAY).*?\))/g, '" + $1 + "')

结果:

{theField} > " + YEAR (today, -3) + " || {theField}  < " + YEAR (today, +3) + "

请注意,我在正则表达式中清理了一点:

  • 从KennyTM注意到的+移除了DAY+
  • [)]+更改为\)
  • 将文字替换字符串从双引号更改为单引号,以便替换文本中的引号不需要转义
  • 删除了您在YEAR和以下左括号之间的结果中添加的额外空间