1

I'm trying to parse all of the text between one or more parentheses and return an array.

For example:

var string = "((CID:34746) OR (CID:8097)) ((CID:34277 OR CID:67300))";
var regex = /\(([^()]+)\)/g;
var results = string.match(regex);
// should result in ["CID:34746","CID:8097","CID:34277 OR CID:67300"]
// but instead is ["(CID:34746)", "(CID:8097)", "(CID:34277 OR CID:67300)"]

I've had 3 people on my team try to find a solution and nobody has. I've looked at all the ones I can find on SO and otherwise. (This one is where I posted the above regex from...)

The closest I've gotten is: /([^()]+)/g.

2 Answers 2

5

.match() will return an array of whole matches only, if you use the global modifier. Use .exec() [MDN] instead:

var match,
    results = [];

while(match = regex.exec(string)) {
    results.push(match[1]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Your regex is correct you're just not using it right:

var string = "((CID:34746) OR (CID:8097)) ((CID:34277 OR CID:67300))";
var regex = /\(([^()]+)\)/g;
var desiredResults = [];
var results;
while( results = regex.exec(string) ) {
    desiredResults.push( results[1] );
}
// now desiredResults is ["CID:34746","CID:8097","CID:34277 OR CID:67300"]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.