正则表达式问题涉及反向抛光计算器 [英] Regexp issue involving reverse polish calculator

查看:86
本文介绍了正则表达式问题涉及反向抛光计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式解决逆向抛光计算器问题,但是在将数学表达式转换为常规形式时遇到问题.

I'm trying to use a regular expression to solve a reverse polish calculator problem, but I'm having issues with converting the mathematical expressions into conventional form.

我写道:

puts '35 29 1 - 5 + *'.gsub(/(\d*) (\d*) (\W)/, '(\1\3\2)')

打印:

35 (29-1)(+5) *

预期

(35*((29-1)+5)) 

但是我得到了不同的结果.我在做什么错了?

but I'm getting a different result. What am I doing wrong?

推荐答案

我假设您是说您尝试过

puts '35 29 1 - 5 + *'.gsub(/(\d*) (\d*) (\W)/, '(\1\3\2)')
                    ^           ^

无论如何,您必须使用量词+而不是*,因为否则您将为\d*匹配一个空字符串作为捕获之一,因此(+5):

Anyway, you have to use the quantifier + instead of *, since otherwise you will match an empty string for \d* as one of your captures, hence the (+5):

/(\d+) (\d+) (\W)/

我会进一步将表达式扩展/约束为类似以下内容:

I would further extend/constrain the expression to something like:

/([\d+*\/()-]+)\s+([\d+*\/()-]+)\s+([+*\/-])/
 |             |  |             |   |
 |             |  |             |   Valid operators, +, -, *, and /.
 |             |  |             |   
 |             |  |             Whitespace.
 |             |  |                 
 |             |  Arbitrary atom, e.g. "35", "(29-1)", "((29-1)+5)".
 |             |                    
 |             Whitepsace.                  
 |
 Arbitrary atom, e.g. "35", "(29-1)", "((29-1)+5)".

...而不是使用gsub,而是在while循环中使用sub,该循环在检测到无法进行更多替换时退出.这非常重要,因为否则会违反操作顺序.例如,查看此Rubular演示.您可以看到,使用gsub可能会替换第二个三重原子"5 + *",而实际上第二次迭代应该在替换第一个三重原子之后替换更早的"三重原子

...and instead of using gsub, use sub in a while loop that quits when it detects that no more substitutions can be made. This is very important because otherwise, you will violate the order of operations. For example, take a look at this Rubular demo. You can see that by using gsub, you might potentially replace the second triad of atoms, "5 + *", when really a second iteration should substitute an "earlier" triad after substituting the first triad!

警告:-(减号)字符必须在字符类中出现 first last ,因为否则它将指定一个范围! (感谢@JoshuaCheek.)

WARNING: The - (minus) character must appear first or last in a character class, since otherwise it will specify a range! (Thanks to @JoshuaCheek.)

这篇关于正则表达式问题涉及反向抛光计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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