javascript 正则表达式 - 字符中的方括号和圆括号-class
javascript regex - brackets and parenthesis in character-class
我想匹配这些字符:javascript 中正则表达式中的字符 class 中的 [] (),我该怎么做?
grep 中的解决方案是:
()
<script>
var text = "echo some text (some text in parenthesis) [some other in brackets]";
var patt = /[][()]/g
console.log(text.match(patt));
</script>
但是这个正则表达式在 JS 中没有提供匹配
您应该转义正则表达式模式中的方括号:
var text = "echo some text (some text in paranthesis) [some other in brackets]",
patt = /[\]\[()]/g;
console.log(text.match(patt)); // ["(", ")", "[", "]"]
您的示例在正则表达式中使用了方括号的特殊含义。如果您希望它们按字面意思匹配,您需要使用 '\' 字符对它们进行转义。您可以检查 this example, and hover over the characters, to see each one's meaning using your example, and this 是否有效。
我想匹配这些字符:javascript 中正则表达式中的字符 class 中的 [] (),我该怎么做?
grep 中的解决方案是:
(
<script>
var text = "echo some text (some text in parenthesis) [some other in brackets]";
var patt = /[][()]/g
console.log(text.match(patt));
</script>
但是这个正则表达式在 JS 中没有提供匹配
您应该转义正则表达式模式中的方括号:
var text = "echo some text (some text in paranthesis) [some other in brackets]",
patt = /[\]\[()]/g;
console.log(text.match(patt)); // ["(", ")", "[", "]"]
您的示例在正则表达式中使用了方括号的特殊含义。如果您希望它们按字面意思匹配,您需要使用 '\' 字符对它们进行转义。您可以检查 this example, and hover over the characters, to see each one's meaning using your example, and this 是否有效。