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.

Community
  • 1
  • 1
Jamie
  • 2,948
  • 4
  • 19
  • 26

2 Answers2

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]);
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
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"]
nobody
  • 10,599
  • 4
  • 26
  • 43