Problem with Regular Expression

M

Mario Ruiz

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...
 
F

F. Senault

Le 19 mai à 18:54, Mario Ruiz 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
 
M

Mark Thomas

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!)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top