Search code examples
rubyregexspace

How do I write a regex that eliminates the space between a number and a colon?


I want to replace a space between one or two numbers and a colon followed by a space, a number, or the end of the line. If I have a string like,

line = "   0 : 28 : 37.02"

the result should be:

"   0: 28: 37.02"

I tried as below:

line.gsub!(/(\A|[ \u00A0|\r|\n|\v|\f])(\d?\d)[ \u00A0|\r|\n|\v|\f]:(\d|[ \u00A0|\r|\n|\v|\f]|\z)/, '\2:\3')
# => "  0: 28 : 37.02"

It seems to match the first ":", but the second ":" is not matched. I can't figure out why.


Solution

  • Excluding the third digit can be done with a negative lookback, but since the other one or two digits are of variable length, you cannot use positive lookback for that part.

    line.gsub(/(?<!\d)(\d{1,2}) (?=:[ \d\$])/, '\1')
    # => "   0: 28: 37.02"