Remove duplicate numbers and operators from a string

I am trying to take a string that is a simple mathematical expression, removes all spaces, removes all duplicate operators, converts them to single-digit numbers, and then evaluates.

For example, a string like "2 7 + * 3 * 95" should be converted to "2 + 3 * 9" and then evaluated as 29.

Here is what I still have:

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

Unfortunately, this does not make single digits and does not remove duplicate operators, as I expected. Any ideas?

+3
source share
2 answers
DATA.each { |expr| 
    expr.gsub!(%r'\s+', '')
    expr.gsub!(%r'([*/+-])[*/+-]+',  '\1')
    expr.gsub!(%r'(\d)\d+', '\1')
    expr.sub!(%r'\A[*/+-]+', '')
    expr.sub!(%r'[*/+-]+\Z', '')
    puts expr + ' = ' + eval(expr).to_s
}

__END__
2 7+*3*95
+-2 888+*3*95+8*-2/+435+-
0
source
"2 7+*3*95".gsub(/([0-9])[0-9 ]*/, '\1').gsub(/([\+\*\/\-])[ +\*\/\-]+/, '\1')

, . , , .

, .

+2

Source: https://habr.com/ru/post/1732715/


All Articles