Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

ruby

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?

like image 387
papaiatis Avatar asked Oct 11 '16 08:10

papaiatis


2 Answers

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"
like image 130
Aleksei Matiushkin Avatar answered Nov 15 '22 08:11

Aleksei Matiushkin


If you need to do that in the context you describe (a key/value separated with : where the value is a domain name), you can simply use:

> s='Domain:............www.google.com'
 => "Domain:............www.google.com" 
> s.gsub(/(?<=[:.])\./, ' ')
 => "Domain:            www.google.com"

Because a domain name doesn't contain a : or consecutive dots.

For a more general use, see @mudasobwa answer or you can do that too:

s.gsub(/(?:\G(?!\A)|\A[^:]*:\K)\./, ' ')

(Where the \G anchor that matches the position after the previous match, forces the next results to be contiguous).

like image 33
Casimir et Hippolyte Avatar answered Nov 15 '22 09:11

Casimir et Hippolyte