How to exclude some words from the search in a regular expression?

Viewed 25

I tried to make some syntax checker for arithmetic expressions. So, one of the negative tests is: No operator between variable(or constant) and left brace. Something like that:

    if (expression.matches(".*[a-zA-Z|0-9]+\\(.*")) {
            throw new IllegalArgumentException("Syntax error in the expression: " + expression);
        }

But I need to use functions(like sin, cos etc.) in expressions in the following format: sin(number), so the test doesn't work, because the rule above says that some operator between "sin" and "(" is needed.

Is it possible to add exceptions in the rule above to use sin, cos, tan, cot, etc.? I mean something like (^sin|cos|tan|cot) Or do I need to edit the syntax rules in my regex at all?

1 Answers

You can use

if (expression.matches(".*[a-zA-Z0-9](?<!\\b(?:co[ts]|tan|sin))\\(.*")) {...}

See the regex demo.

Details:

  • .* - any zero or more chars other than line break chars as many as possible
  • [a-zA-Z0-9] - an alphanumeric char
  • (?<!\b(?:co[ts]|tan|sin)) - a negative lookahead that fails the match if there is cos, cot, tan or sin whole word immediately to the left of the current location
  • \( - a literal ( char
  • .* - any zero or more chars other than line break chars as many as possible.
Related