简体   繁体   English

string.replace不适用于正则表达式

[英]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: 还有两件事:

  1. It's better to escape all curly brackets. 最好不要使用所有花括号。 Your pattern will work well without escaping them, but it's a good idea to indicate that it's just a regular text. 您的模式在不转义的情况下将可以很好地工作,但是最好将其表示为常规文本。
  2. Parentheses are redundant in your case, because you don't do anything with the catched string between curly braces. 在您的情况下,括号是多余的,因为对于花括号之间的字符串,您不执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM