- Split on URI regular expression; include the URI's in the result.
- For each piece:
- if it is a URI, leave it alone
- otherwise, do word replacement
- Join the pieces
Code:
# From RFC 3986 Appendix B, with these modifications:
# o Spaces disallowed
# o All groups non-matching, except for added outermost group
# o Not anchored
# o Scheme required
# o Authority required
URI_REGEX = %r"((?:(?:[^ :/?#]+):)(?://(?:[^ /?#]*))(?:[^ ?#]*)(?:\?(?:[^ #]*))?(?:#(?:[^ ]*))?)"
def replace_except_uris(text, old, new)
text.split(URI_REGEX).collect do |s|
if s =~ URI_REGEX
s
else
s.gsub(old, new)
end
end.join
end
text = <<END
stack http://www.stackoverflow.com stack
stack http://www.somewhere.come/stack?stack=stack#stack stack
END
puts replace_except_uris(text, /stack/, 'LINKED-LIST')
# => LINKED-LIST http://www.stackoverflow.com LINKED-LIST
# => LINKED-LIST http://www.somewhere.come/stack?stack=stack#stack LINKED-LIST