papaiatis papaiatis - 1 month ago 12
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:

Domain:...................google.com


I need this to be:

Domain: google.com


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

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


But it isn't sufficient because it produces:

Domain: google.com


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

Answer

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

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