如何区分令牌运算符的'-'运算符和负数 [英] How to differentiate '-' operator from a negative number for a tokenizer

查看:155
本文介绍了如何区分令牌运算符的'-'运算符和负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个中缀表达式解析器,所以我必须创建一个标记器.效果很好,除了一件事:我现在不知道如何将负数与-"运算符区分开.

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.

例如,如果我有:

23 / -23

令牌应该是23/-23,但是如果我有类似

The tokens should be 23, / and -23, but if I have an expression like

23-22

然后令牌应为23-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

它获得以下令牌的位置:--56它应获得--56

where it gets the following tokens: - and -56 where it should get --56

有什么建议吗?

推荐答案

在第一个示例中,令牌应为23/-23.

In the first example the tokens should be 23, /, - and 23.

然后的解决方案是根据关联性和优先级规则评估令牌.例如,-不能绑定到/,但是可以绑定到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.

如果遇到--56,则将其拆分为--56,并且规则将解决此问题.不需要特殊情况.

If you encounter --56, is split into -,-,56 and the rules take care of the problem. There is no need for special cases.

这篇关于如何区分令牌运算符的'-'运算符和负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆