问题
I am creating an infix expression parser, an so I have to create a tokenizer. It works well, except for one thing: I do not now how to differentiate negative number from the "-" operator.
For example, if I have:
23 / -23
The tokens should be 23, / and -23, but if I have an expression like
23-22
Then the tokens should be 23, - and 22.
I found a dirty workaround which is if I encounter a "-" followed by a number, I look at the previous character and if this character is a digit or a ')', I treat the "-" as an operator and not a number. Apart from being kind of ugly, it doesn't work for expressions like
--56
where it gets the following tokens: - and -56 where it should get --56
Any suggestion?
回答1:
In the first example the tokens should be 23, /, - and 23.
The solution then is to evaluate the tokens according to the rules of associativity and precedence. - cannot bind to / but it can to 23, for example.
If you encounter --56, is split into -,-,56 and the rules take care of the problem. There is no need for special cases.
来源:https://stackoverflow.com/questions/26529711/how-to-differentiate-operator-from-a-negative-number-for-a-tokenizer