Reputation: 53884
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.
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('{[()]}')); // ['()']
Upvotes: 2
Views: 54
Reputation: 41
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.
Upvotes: 0
Reputation: 37755
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
const matchType = str => str.match(/[()]/g)
console.log(matchType('{(})[]')); // ['(',')]
// Expected ['(',')']
console.log(matchType('{[()]}'));
Upvotes: 4