You should not use regex for this. Instead, you can iterate over the character of a string by character and track the level of nesting.
Initially, nesting is 0. When you see ( , increase nesting by 1, and when you see ) , reduce nesting. The expression is correctly balanced if the final nesting is 0, and the nesting never drops below 0.
public static boolean checkParentheses(String s) { int nesting = 0; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); switch (c) { case '(': nesting++; break; case ')': nesting--; if (nesting < 0) { return false; } break; } } return nesting == 0; }
Mark byers
source share