我正在尝试获取一个字符串,它是一个简单的数学表达式,删除所有空格,删除所有重复的运算符,转换为单个数字,然后计算。
例如,像“2 7+*3*95”这样的字符串应该转换为“2+3*9”,然后计算为29。
这是我目前所拥有的:
expression.slice!(/ /) # Remove whitespace
expression.slice!(/\A([\+\-\*\/]+)/) # Remove operators from the beginning
expression.squeeze!("0123456789") # Single digit numbers (doesn't work)
expression.squeeze!("+-*/") # Removes duplicate operators (doesn't work)
expression.slice!(/([\+\-\*\/]+)\Z/) # Removes operators from the end
puts eval expression
不幸的是,这并没有像我预期的那样生成个位数,也没有删除重复的运算符。有什么想法吗?
最佳答案
"2 7+*3*95".gsub(/([0-9])[0-9 ]*/, '\1').gsub(/([\+\*\/\-])[ +\*\/\-]+/, '\1')
第一个正则表达式处理个位数,第二个处理重复运算符。如果您真的愿意,您可以将它压缩成一个正则表达式。
这适用于一个快速而肮脏的解决方案,但你可能会得到一个合适的解析器更好的服务。
关于ruby - 从字符串中删除重复的数字和运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2260278/