Reputation: 325
I have a string that looks like this:
(Boxing [email protected]@To punch and kick)([email protected]@To keep money in)
How can I extract the contents within the parenthesis so I get 2 strings:
Boxing [email protected]@To punch and kick
[email protected]@To keep money in
What would be the regex for this using JavaScript?
Upvotes: 1
Views: 750
Reputation: 9859
I created a little javascript library called balanced to help with tasks like this. As mentioned by @Paulpro the solution breaks if you have content in between the parenthesis, which is what balanced is good at.
var source = '(Boxing [email protected]@To punch and kick)Random Text([email protected]@To keep money in)';
var matches = balanced.matches({source: source, open: '(', close: ')'}).map(function (match) {
return source.substr(match.index + match.head.length, match.length - match.head.length - match.tail.length);
});
// ["Boxing [email protected]@To punch and kick", "[email protected]@To keep money in"]
heres a JSFiddle example
Upvotes: 0
Reputation: 141927
Using suat's regex, and since you want to do global matching with groups, you need to use a loop to get all the matches:
var str = '(Boxing [email protected]@To punch and kick)([email protected]@To keep money in)';
var regex = new RegExp('\\((.*?)\\)', 'g');
var match, matches = [];
while(match = regex.exec(str))
matches.push(match[1]);
alert(matches);
// ["Boxing [email protected]@To punch and kick", "[email protected]@To keep money in"]
Upvotes: 2
Reputation: 82088
This regex /[^()]+/g
matches all series of characters which are not (
or )
:
var s = '(Boxing [email protected]@To punch and kick)'+ // I broke this for readability
'([email protected]@To keep money in)'.match(/[^()]+/g)
console.log(s) // ["Boxing [email protected]@To punch and kick",
// "[email protected]@To keep money in"]
Upvotes: 1