How to differentiate '-' operator from a negative number for a tokenizer

社会主义新天地 提交于 2019-12-10 13:34:01

问题


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

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