papaiatis papaiatis - 5 months ago 23
Ruby Question

Ruby regex - replace dots with spaces in the middle of text

I have a long text in which I'd like to replace dots with spaces but only in the middle of the text.
For example:

I need this to be:


I came upon this regex that replaces the dots with a single space:

str.gsub!(/(?<=:)\.+(?=[^\.])/, ' ')

But it isn't sufficient because it produces:


I need to keep as many spaces as dots were.
How would you solve it?


You are nearly there, your regexp is fine, just use block version of String#gsub to calculate the length of match for replacement:

▶ str = ''
#⇒ ""
▶ str.gsub(/(?<=:)\.+(?=[^\.])/) { |m| ' ' * m.length }
#⇒ "Domain:         "