当字符串包含括号时如何配置正则表达式

发布于 2025-01-03 06:41:39 字数 404 浏览 1 评论 0原文

我确信这很简单,但我在网上找不到。

此代码:

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

失而复得 2025-01-10 06:41:39

通过双反斜杠 \\ 转义括号。试试这个。

    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);

演示

Escape the brackets by double back slashes \\. Try this.

    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);

Demo

无悔心 2025-01-10 06:41:39

您需要转义要从中创建正则表达式的字符串中包含的特殊字符。例如,定义此函数:

function escapeRegex(string) {
  return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\
amp;');
}

并使用它将结果分配给您的 bad_string 变量:

let bad_string = "bar(arg)"
bad_string = escapeRegex(bad_string)

// You can now use the string to create the Regex :v:

You need to escape the special characters contained in string you are creating your Regex from. For example, define this function:

function escapeRegex(string) {
  return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\
amp;');
}

And use it to assign the result to your bad_string variable:

let bad_string = "bar(arg)"
bad_string = escapeRegex(bad_string)

// You can now use the string to create the Regex :v:
℉絮湮 2025-01-10 06:41:39

您的正则表达式定义字符串应该是:

var bad_string = "bar\\(arg\\)";

使用正则表达式时需要对特殊字符进行转义,并且因为您在字符串中构建正则表达式,所以您需要对转义字符进行转义 :P

http://www.regular-expressions.info/characters.html

Your RegEx definition string should be:

var bad_string = "bar\\(arg\\)";

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文