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?
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"
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With