2

How can I check syntax in a string which will contain basic mathematical operators +-/* and variables containing alphanumerical chars. This string also can contain brackets (). It is important to know if it's complete, meaning by closing brackets or no redudant operators.

For example (1*3(3+2)+test) is valid, but ((1++2) is not.

Is this possible in Javascript using regex? Or do I have to make an algorithm, if so, has someone a similar algorithm for that?

Cœur
  • 37,241
  • 25
  • 195
  • 267
datprog
  • 31
  • 4
  • 1
    possible duplicate of [Validate mathematical expressions using regular expression?](http://stackoverflow.com/questions/11009320/validate-mathematical-expressions-using-regular-expression) – michelem Aug 25 '15 at 14:56
  • 1
    Ordinary regular expressions are not powerful enough to match all possible combinations of nested parentheses. Even if the only legal strings are "0", "(0)", "((0))", "(((0)))", etc, there is no regex that matches them all. – Kevin Aug 25 '15 at 14:56
  • @Michelem Close, but it doesn't handle variables and parentheses. – Luaan Aug 25 '15 at 14:56
  • 1
    I doubt that you will be able to do the parenthesis with a regular expression. But an algorithm to make sure there are no wrong ones isn't difficult. Just parse from left to right counting +1 for an opening parenthesis and -1 for a closing one. When the counter ever goes to -1, there is a closing parenthesis without an opening one. When the counter is larger than 0 at the end, there is an opening one without a closing one. – Philipp Aug 25 '15 at 14:57
  • @Philipp It's not that simple - you missed `()`, `( )` etc. In the end, a full fledged parser might be required to make this work properly. – Luaan Aug 25 '15 at 14:58
  • the possible duplicate does not support nested brackets... – datprog Aug 25 '15 at 15:01

1 Answers1

1

Regular expressions on their own aren't equipped to parse these sort of expressions since you would need to have some sort of stack through which you would check what has been matched before.

You would need to create a simple parser which goes through the string and checks the following:

  1. If you found a number/text, move forward.
  2. If you found an opening bracket, push it to stack.
  3. If you found a closing bracket, pop one bracket from the stack (described in step 2). If you have missing opening brackets, this would result in attempting to pop from an empty stack, which should raise an error.
  4. If you found an operator, ensure that the next character is an opening bracket or another number/text. This should help break in situations where you have two operators following each other or else a string ending with an operator.

Once that the parser finishes, check to see if the stack you used to keep track of brackets is not empty. If it is not empty, you have an unbalanced amount of brackets.

npinti
  • 51,780
  • 5
  • 72
  • 96