[英]string.replace does not work with regex
I have this string dfdfd dsfsdfsdfsdf {{random.number}} dsfdsfsdfsdf {{bla}}
and simple code that shold replace any {{...}}
in a given string: 我有以下字符串
dfdfd dsfsdfsdfsdf {{random.number}} dsfdsfsdfsdf {{bla}}
和简单的代码(可替换给定字符串中的任何{{...}}
:
const b = template.replace(/\{{(.*)\}}/g, 'aaaa');
but nothing happened template.replace
just does not work however the regex seems to be matching all {{}}
但
template.replace
却什么也没发生,但是正则表达式似乎与所有{{}}
都匹配
Any thougts? 有什么想法吗?
UPDATE: 更新:
Just realized that my input string was wrong. 刚刚意识到我的输入字符串是错误的。 Now I have all working with my original regex.
现在我都在使用原始正则表达式了。 However thanks to @Robo-Robok now I learned about
greedy
regexes and will be using his regex intstead. 但是,由于有了@ Robo-Robok,现在我了解了
greedy
的正则表达式,并将继续使用他的正则表达式。
Regular expressions are greedy by default. 默认情况下,正则表达式是贪婪的。 Your
.*
eats as much as it can, which includes the first }}
pair. 您的
.*
尽可能多地吃东西,其中包括第一对}}
。
Try this instead: 尝试以下方法:
const b = template.replace(/\{\{.*?\}\}/g, 'aaaa');
Question mark after *
, ?
*
之后的问号?
makes the match non-greedy. 使匹配不贪心。
Also two things: 还有两件事:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.