Forum: Ruby Problem with Regular Expression

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Mario R. (Guest)
on 2009-05-19 20:54
I'm replacing a string using:
xmlString.gsub!(/:#{tagName}>#{oldValue}<\//i,":" + tagName + ">" +
value + "</")

It works perfectly but... if oldValue contains the character +, it
doesn't work.

Do you know how to solve this?

Thanks a lot...
Aaron P. (Guest)
on 2009-05-19 21:05
(Received via mailing list)
On Wed, May 20, 2009 at 01:54:24AM +0900, Mario R. wrote:
>
> I'm replacing a string using:
> xmlString.gsub!(/:#{tagName}>#{oldValue}<\//i,":" + tagName + ">" +
> value + "</")
>
> It works perfectly but... if oldValue contains the character +, it
> doesn't work.
>
> Do you know how to solve this?

Use Regexp.escape():

  xmlString.gsub!(/:#{tagName}>#{Regexp.escape(oldValue)}<\//i,":" +
tagName + ">" +
    value + "</")
F. Senault (Guest)
on 2009-05-19 21:06
(Received via mailing list)
Le 19 mai à 18:54, Mario R. a écrit :

> I'm replacing a string using:
> xmlString.gsub!(/:#{tagName}>#{oldValue}<\//i,":" + tagName + ">" +
> value + "</")
>
> It works perfectly but... if oldValue contains the character +, it
> doesn't work.
>
> Do you know how to solve this?

When you interpolate strings into a regexp, the special chars are taken
as part of the regexp (meaning your '+' means one or more of the
expression before).  If you want to match literals, use Regexp.escape :

xmlString.gsub!(/:#{Regexp.escape(tagName)}>#{Regexp.escape(oldValue)}<\//i
...

>> Regexp.escape("abc+")
=> "abc\\+"
>> Regexp.escape("abc[]+")
=> "abc\\[\\]\\+"

Fred
Mario R. (Guest)
on 2009-05-19 21:13
F. Senault wrote:
> Le 19 mai � 18:54, Mario R. a �crit :
>

Yep It works!!!

Thank you very much.
Mark T. (Guest)
on 2009-05-20 15:31
(Received via mailing list)
On May 19, 12:54 pm, Mario R. <removed_email_address@domain.invalid> wrote:
> I'm replacing a string using:
> xmlString.gsub!(/:#{tagName}>#{oldValue}<\//i,":" + tagName + ">" +
> value + "</")

In general, it's not a good idea to parse XML with regular
expressions. They tend to be more fragile. What happens if there is an
attribute on the tag? Extra spaces around the brackets? The expression
breaks.

If you want something more robust, use an XML parser. As a bonus, your
code will also be more readable.

doc = Nokogiri::XML(xmlString)
doc.xpath("//mytag").each do |tag|
  tag.content = value
end

-- Mark

(I'm surprised Aaron didn't respond with such an example!)
This topic is locked and can not be replied to.