我想匹配字符串中所有给定的 (
和 )
,但我遇到了麻烦,因为我当前的解决方案匹配 ()
而我的意图是得到像 ['(',')']
我的regex
表达式为:/[()]+/g
, Regex101 playground .
如何仅使用正则表达式表达式获得所需的行为?
const matchType = str => str.match(/[()]+/g)
console.log(matchType('{(})[]')); // ['(',')]
// Expected ['(',')']
console.log(matchType('{[()]}')); // ['()']
最佳答案
不要使用量词+
,
当您使用+
量词时+
表示一次或多次,
[()]+
这意味着匹配 ( 或 )
一次或多次,因此当您有像 ()
这样的字符串时,它会考虑作为一场比赛
const matchType = str => str.match(/[()]/g)
console.log(matchType('{(})[]')); // ['(',')]
// Expected ['(',')']
console.log(matchType('{[()]}'));
关于javascript - 如何分割正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58031653/