Regex for matching Functions and Capturing their Arguments

后端 未结 5 821
自闭症患者
自闭症患者 2020-12-02 17:37

I\'m working on a calculator and it takes string expressions and evaluates them. I have a function that searches the expression for math functions using Regex, retrieves the

5条回答
  •  有刺的猬
    2020-12-02 18:08

    I'm sorry to burst the RegEx bubble, but this is one of those things that you just can't do effectively with regular expressions alone.

    What you're implementing is basically an Operator-Precedence Parser with support for sub-expressions and argument lists. The statement is processed as a stream of tokens - possibly using regular expressions - with sub-expressions processed as high-priority operations.

    With the right code you can do this as an iteration over the full token stream, but recursive parsers are common too. Either way you have to be able to effectively push state and restart parsing at each of the sub-expression entry points - a (, , or ( token - and pushing the result up the parser chain at the sub-expression exit points - ) or , token.

提交回复
热议问题