当字符串包含括号时如何配置正则表达式
我确信这很简单,但我在网上找不到。
此代码:
var new_html = "foo and bar(arg)";
var bad_string = "bar(arg)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
将 bad_start 设置为 -1(未找到)。如果我删除 (arg),它会按预期运行 (bad_start == 8)。我可以做些什么来使(非常方便的)“新正则表达式”语法起作用,还是我必须找到另一种方法?这个例子很简单,但在真正的应用程序中它将进行全局搜索和替换,所以我需要正则表达式和“g”。或者我也这样?
TIA
I'm sure this is an easy one, but I can't find it on the net.
This code:
var new_html = "foo and bar(arg)";
var bad_string = "bar(arg)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
sets bad_start to -1 (not found). If I remove the (arg), it runs as expected (bad_start == 8). Is there something I can do to make the (very handy) "new Regexp" syntax work, or do I have to find another way? This example is trivial, but in the real app it would be doing global search and replace, so I need the regex and the "g". Or do I?
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过双反斜杠 \\ 转义括号。试试这个。
演示
Escape the brackets by double back slashes \\. Try this.
Demo
您需要转义要从中创建正则表达式的字符串中包含的特殊字符。例如,定义此函数:
并使用它将结果分配给您的
bad_string
变量:You need to escape the special characters contained in string you are creating your Regex from. For example, define this function:
And use it to assign the result to your
bad_string
variable:您的正则表达式定义字符串应该是:
使用正则表达式时需要对特殊字符进行转义,并且因为您在字符串中构建正则表达式,所以您需要对转义字符进行转义 :P
http://www.regular-expressions.info/characters.html
Your RegEx definition string should be:
Special characters need to be escaped when using RegEx, and because you are building the RegEx in a string you need to escape your escape character :P
http://www.regular-expressions.info/characters.html