java method for parsing nested expressions

后端 未结 5 1207
Happy的楠姐
Happy的楠姐 2020-12-16 04:37

lets say I\'ve written a function to evaluate a simple mathematical operation, and I have some user input in a string such as: \"1 + [2 + [3+4]]\" How can I parse these squa

相关标签:
5条回答
  • 2020-12-16 05:00

    The cleanest way to accomplish your goal is to write a Lexer and a Parser for this purpose. Writing a recursive descent parser is not that hard to do from scratch for arithmetic expressions.

    There are numerous code examples on the web. This is an example that you could use for inspiration.

    The Lexer is there to normalize your input and to abstract it to a stream of tokens. This way, your Parser only needs to work on tokens instead of additionally having to deal with whitespace issues and other annoying things.

    Two examples for high-level algorithms that are stack-based, another example that shows a recursive descent approach.

    0 讨论(0)
  • 2020-12-16 05:02

    I think regex is not a good choice to achieve this functionality

    You should convert user expression to postfix or prefix notation and then build an expression tree from them. This is a standard approach in CS (language does not really matter here) to solve this issue in a clean way

    0 讨论(0)
  • 2020-12-16 05:05

    For Java, you could use JavaCC for parser/lexer. I have used this one in numerous projects. It's pretty easy to use. One of the examples, I think, includes an arithmetic parsing. JavaCC will build the syntax tree where you could walk through.

    Trying out arithmetic using JavaCC would give good intro to Context Free Grammar and the concept of Abstract Syntax Tree. If you are learning, then it is a good step to take after trying out what @emboss suggested

    0 讨论(0)
  • 2020-12-16 05:06

    Use a stack. When you encounter an open bracket, push whatever you're working on onto the stack and start the new expression. When you hit a closing bracket, pop the stack and use the expression you just calculated as the next item. Or, as previous posters have said, use recursion or a tree.

    0 讨论(0)
  • 2020-12-16 05:08

    Recursion works well for these:

    int parse(String expression){
        //use a regex to find an instance of [ followed by numbers/operators, followed by ]
        //replace it with parse(whatever's inside the brackets)
        //continue until there are none left
        //evaluate the string (which should be a sequence of numbers and operators without brackets)
    }
    
    0 讨论(0)
提交回复
热议问题