Am I correct in thinking that Regex can\'t be used to detect missing parentheses (because there is no way of counting pairs)? Using JavaScript I\'ve about a thousand strings
You can't do the recursion in the regex itself, but you can always do it in JavaScript.
Here is an example:
// First remove non-brackets:
string=string.replace(/[^{}[\]()]/g,"");
// Then remove bracket pairs recursively
while (string!==oldstring) {
oldstring=string;
string=string.replace(/({}|\[\]|\(\))/g,"");
}
The remainder are the non-matching brackets.
Live demo: http://jsfiddle.net/3Njzv/
If you need to count the pairs, you can do the replacements one at a time and add a counter:
// First remove non-brackets:
string=string.replace(/[^{}[\]()]/g,"");
// Then remove bracket pairs recursively
var counter=-1;
while (string!==oldstring) {
counter ++;
oldstring=string;
string=string.replace(/({}|\[\]|\(\))/,"");
}