我有一个看起来像这样的字符串:
{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) + "
有没有人有任何想法?
答案 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) + "
请注意,我在正则表达式中清理了一点:
+
移除了DAY+
[)]+
更改为\)