Reputation: 52590
I'm trying to replace all example.com
instances with <a href="http://example.com">example.com</a>
in a string:
content.gsub(/example\.com/, '<a href="http://example.com">example.com</a>')
But I don't want to replace example.com
if there's a dot before it, like in www.example.com
. So my first thought is to make the regular expression /[^\.]example.com/
. But then, of course, gsub!
will replace the character before example.com
too.
Is there an easy way to replace all the example.com
s that don't have a .
in front, in Ruby?
Upvotes: 0
Views: 212
Reputation: 47872
I would do this with a negative lookbehind:
content.gsub(/((?<!\.)example.com)/i , '<a href="http://\1">\1</a>')
The part that says (?<!\.)
literally means "if not preceded by a .
".
A negative look-behind is a zero-width assertion, so it is not part of the match, and therefore won't be replaced.
Note that these are only supported in Ruby 1.9+
This example also captures the domain itself so that it can be used in the replace, which makes it easy to swap it out with a variable, and I made it case insensitive (by ending the expression with /i
) just because it made more sense to me.
Upvotes: 2
Reputation: 786289
You can use back reference
in gsub
:
content.gsub(/(^|[^.])example\.com/, '\\1<a href="http://example.com">example.com</a>')
(^|[^.])
will match start of input or non dot character.
Upvotes: 1