at.
at.

Reputation: 52590

Regular expression to replace a value in Ruby

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.coms that don't have a . in front, in Ruby?

Upvotes: 0

Views: 212

Answers (2)

briantist
briantist

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

anubhava
anubhava

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

Related Questions