Matching math expression with regular expression?

前端 未结 8 2059
旧时难觅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:10

    I believe you will be better off implementing a real parser to accomplish what you're after.

    A parser for simple mathematical expressions is "Parsing 101", and there are several examples to be found online.

    Some examples include:

    • ANTLR: Expression Evaluator Sample (ANTLR grammars can target several languages)
    • pyparsing: http://pyparsing.wikispaces.com/file/view/fourFn.py (pyparsing is a Python library)
    • Lex & Yacc: http://epaperpress.com/lexandyacc/ (contains a PDF tutorial and sample code for a calculator)

    Note that the grammar you will need for validating expressions is simpler than the examples above, since the examples also implement evaluation of the expression.

提交回复
热议问题