简体   繁体   English

javascript正则表达式-字符类中的括号和括号

[英]javascript regex - brackets and parenthesis in character-class

I would like to match these characters: [] () in a character class in a regex in javascript, how can I do that? 我想匹配以下字符:[]()在javascript的正则表达式中的字符类中,该怎么做?

The solution in grep would be: ( regex - brackets and parenthesis in character-class ) grep中的解决方案是:( regex-字符类中的括号和括号

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

But this regex provides no match in JS 但是此正则表达式在JS中没有匹配项

You should escape the square brackets inside the regex pattern: 您应该转义正则表达式模式内的方括号:

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

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

Your example uses square brackets' special meaning in regex. 您的示例在正则表达式中使用方括号的特殊含义。 If you want them to be matched literally you need to escape them using the '\\' character. 如果要从字面上匹配它们,则需要使用'\\'字符对其进行转义。 You can check this example, and hover over the characters, to see each one's meaning using your example, and this for the working one. 您可以查看示例,并将其悬停在各个字符上,以使用示例查看每个人的意思,而对于工作中的例子来说,则是这样

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

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