[英]How to split regex matches
I would like to match all given (
and )
in a string, but I'm having trouble because of my current solution matches ()
while my intention is got a split result like ['(',')']
我想在一个字符串中匹配所有给定的
(
和)
,但是由于我当前的解决方案匹配()
而我的意图是得到像['(',')']
这样的拆分结果,所以我遇到了麻烦
My regex
expression is: /[()]+/g
, Regex101 playground .我的
regex
表达式是: /[()]+/g
, Regex101 playground 。
How can I manage to get the desired behavior only with a regex expression?如何仅使用正则表达式才能获得所需的行为?
const matchType = str => str.match(/[()]+/g) console.log(matchType('{(})[]')); // ['(',')] // Expected ['(',')'] console.log(matchType('{[()]}')); // ['()']
Do not use quantifier +
,不要使用量词
+
,
when you use +
quantifier +
it means one or more time,当你使用
+
量词+
时,它表示一个或多个时间,
[()]+
this means match ( or )
one or more time, so when you have string like ()
it consider it as a single match [()]+
这意味着匹配( or )
一次或多次,因此当您有类似()
的字符串时,它会将其视为单个匹配
const matchType = str => str.match(/[()]/g) console.log(matchType('{(})[]')); // ['(',')] // Expected ['(',')'] console.log(matchType('{[()]}'));
You just need to get rid of the +
:你只需要摆脱
+
:
const matchType = str => str.match(/[()]/g)
The +
means that you will match on one or more parens. +
表示您将匹配一个或多个括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.