2016-05-20 34 views
0

我想在javascript中的正則表達式的字符類中匹配這些字符:[](),我該怎麼做?javascript正則表達式 - 字符類中的括號和parentesis

在grep的解決辦法是: (regex - brackets and parenthesis in character-class

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

但這個表達式在JS

提供敵不過
+1

您需要在括號表達式中隱藏方括號,如'/ [\] [()]/g' –

回答

0

你應該逃脫方括號中的正則表達式模式中:

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

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

你的例子在正則表達式中使用方括號的特殊含義。如果你想讓它們按字面匹配,你需要使用'\'字符來轉義它們。你可以檢查this的例子,並將鼠標懸停在角色上,使用你的例子查看每個角色的意義,並且使用this作爲工作角色。

相關問題