Problem: is the expression syntax correct?
Rules: goes from left to right numbers of left and right brackets should be the same, and open-close in good convention, first left, example:
(xxx(xx)()) - OK
((())) - OK
(x(x(x(x(x))X)x)x) - OK
(()() - WRONG
)() - WRONG
My solution:
private boolean syntaxValidator(String str) {
if (StringUtils.isBlank(str)) {
return false;
} else {
int counter = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '(') {
counter++;
} else if (str.charAt(i) == ')') {
counter--;
if (counter < 0) {
return false;
}
}
}
if (counter == 0) {
return true;
} else {
return false;
}
}
}
Is it effective? Can it be solved by using regular expression? How?
Is it effective?
Yes, in my opinion, provided you incorporate the advice in the other answer.Typically how this is done for validating multiple types of brackets is by using a stack. Push a character on the top of the character, if it is an opening bracket kind of character (one of (, [, { ). While encountered a closing kind of character (), }, ] ), pop the stack and compare the current and the popped character. If no equal, then you have a syntax error.
Can it be solved by using regular expression?
This is not a job of regex. Bracket validation would typically require you to have some kind of count (like you are doing now). Regex by nature does not maintain any count at all. Although, I think, this is possible by using PCRE, I do not remember it now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With