Assuming you can insert parentheses, you cannot do this with direct regular expressions, because you cannot check arbitrary nested parentheses with a regular expression.
A more typical way of checking this input is to split the process into two steps. Use the regex family to tokenize input, and then use a simple grammar to validate the resulting token sequence. LALR (1) grammar, such as yacc support, makes this problem trivial.
I think there are several extended forms of regular expressions that add the necessary functionality that could correspond to arbitrarily nested parentheses. I must admit that I am not very familiar with any of them, since they quickly become more complicated to use than just writing some loop logic around a much simpler set of matches.
source share