Regex to find unmatched parentheses
13:43 15 Feb 2012

I need a regular expression that can find any unmatched brace (opening or closing) in a string potentially containing matching parentheses.

The question exists here on stackoverflow, but I haven't found a regex-based solution that works.

I came up with a regex that finds unmatched open braces \((?![^)]+\)) using a negative lookahead, but I can't seem to figure out the opposite one required for unmatched closing braces.

EDIT: The above regex to find unmatched open braces doesn't work as intended. E.g. it will miss cases where multiple open braces are followed by a single closing brace (see also comments)

Here is my test string that I've been experimenting with on Rubular:

one) ((two) (three) four) (five)))

Note that the string can contain any type of character, including quotes, dashes, etc.

ruby regex