Matching math expression with regular expression?

前端 未结 8 2061
旧时难觅i
旧时难觅i 2020-11-27 18:36

For example, these are valid math expressions:

a * b + c
-a * (b / 1.50)
(apple + (-0.5)) * (boy - 1)

And these are invalid math expression

相关标签:
8条回答
  • 2020-11-27 19:12

    Use a pushdown automaton for matching paranthesis http://en.wikipedia.org/wiki/Pushdown_automaton (or just a stack ;-) )

    Details for the stack solution:

    while (chr available)
        if chr == '(' then
          push '('
        else
          if chr == ')' then
            if stack.elements == 0 then
              print('too many or misplaced )')
              exit
            else
              pop //from stack
    end while
    if (stack.elements != 0)
      print('too many or misplaced(')
    

    Even simple: just keep a counter instead of stack.

    0 讨论(0)
  • 2020-11-27 19:13

    For parenthesis matching, and implementing other expression validation rules, it is probably easiest to write your own little parser. Regular expressions are no good in this kind of situation.

    0 讨论(0)
提交回复
热议问题