Regex for matching Functions and Capturing their Arguments

后端 未结 5 841
自闭症患者
自闭症患者 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:14

    Regular expressions aren't going to get you completely out of trouble with this...

    Since you have nested parentheses, you need to modify your code to count ( against ). When you encounter an (, you need to take note of the position then look ahead, incrementing a counter for each extra ( you find, and decrementing it for each ) you find. When your counter is 0 and you find a ), that is the end of your function parameter block, and you can then parse the text between the parentheses. You can also split the text on , when the counter is 0 to get function parameters.

    If you encounter the end of the string while the counter is 0, you have a "(" without ")" error.

    You then take the text block(s) between the opening and closing parentheses and any commas, and repeat the above for each parameter.

提交回复
热议问题