【问题标题】:javascript regex - brackets and parenthesis in character-classjavascript regex - 字符类中的括号和括号
【发布时间】:2016-05-20 21:31:58
【问题描述】:

我想匹配这些字符: [] () 在 javascript 中的正则表达式中的字符类中,我该怎么做?

grep 中的解决方案是: (regex - brackets and parenthesis in character-class)

<script>
var text = "echo some text (some text in parenthesis) [some other in brackets]";
var patt = /[][()]/g
console.log(text.match(patt));
</script>

但是这个正则表达式在 JS 中没有提供匹配

【问题讨论】:

  • 需要在括号表达式中转义右方括号,如/[\][()]/g

标签: javascript regex special-characters


【解决方案1】:

您应该转义正则表达式模式中的方括号:

var text = "echo some text (some text in paranthesis) [some other in brackets]",
    patt = /[\]\[()]/g;

console.log(text.match(patt));  // ["(", ")", "[", "]"]

【讨论】:

    【解决方案2】:

    您的示例在正则表达式中使用方括号的特殊含义。如果您希望它们在字面上匹配,则需要使用 '\' 字符对它们进行转义。您可以查看this 示例,并将鼠标悬停在字符上,以使用您的示例查看每个字符的含义,并查看this 用于工作的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多