Ka Mok Ka Mok - 1 year ago 69
Ruby Question

How to split string using regex to split between +,-,*,/ symbols?

I need to tell Ruby in regex to

before and after the
+ - * /
symbols in my program.


I need to turn
[1.0, "+", 12.0]

[6.0, "/", 0.25]

There could be cases like
but highly unlikely. If first two I listed above are satisfied it should be good.

On the Ruby docs,
"hi mom".split(%r{\s*}) #=> ["h", "i", "m", "o", "m"]

I looked up a cheat-sheet to try to understand
, and I know that the stuff inside
such as
are skipped and \s means white space in regex.

Answer Source

I think this could be useful:

"1.2+3.453".split('+').flat_map{|elem| [elem, "+"]}[0...-1]
# => ["1.2", "+", "3.453"]
"1.2+3.453".split('+').flat_map{|elem| [elem.to_f, "+"]}[0...-1]
# => [1.2, "+", 3.453]

Obviously this work only for +. But you can change the split character.


This version work for every operator

"1.2+3.453".split(%r{(\+|\-|\/|\*)}).map do |x|
    unless x =~ /(\+|\-|\/|\*)/ then x.to_f else x end
# => [1.2, "+", 3.453]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download