String.replace() returns unwanted string

我们两清 提交于 2019-12-04 14:13:00

You're right, String.replace is not the right tool for the job here.

What you want to do is to tokenize the input string, then operate on the tokens. Optionally you can combine back into a string at the end, but it depends on what you intend to do with the formula.

For example, you want to tokenize the string "(1+2+3)>100" into the array ["(", "1", "+", "2", "+", "3", ")", ">", "100"]. This is simply a matter of splitting on every boundary between a digit and a symbol.

From this representation, it's a simple matter to replace the entire tokens in the array with their corresponding values, e.g. find the array index that has value "1" and replace it with "30.0", etc. Then you can create a new expression string by just joining all the parts in the array back together.

If you want to go one step further, you can translate into an expression tree, which would look something like this:

OpGreaterThan
    OpPlus
        Symbol(1)
        OpPlus
            Symbol(2)
            Symbol(3)
    Literal(100)

This tree is formed by transforming the input expression (which is rendered in standard infix notation) into reverse polish notation, then building a tree where each node is an operator and its children are operands. This would allow you to symbolically manipulate and/or evaluate the formula.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!