Dennis Vash
Dennis Vash

Reputation: 53884

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.

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

Answers (2)

Michael Smith
Michael Smith

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

Code Maniac
Code Maniac

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

Related Questions