[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Problem with Regular Expression

Mario Ruiz

5/19/2009 4:54:00 PM


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...
--
Posted via http://www.ruby-....

4 Answers

F. Senault

5/19/2009 5:02:00 PM

0

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
--
When your pubic hair's on fire, something's wrong
When you think you're the Messiah, something's wrong
When you mistake a plane for Venus, something's wrong
When your girlfriend's got a penis... (K's Choice, Something's wrong)

Aaron Patterson

5/19/2009 5:05:00 PM

0

On Wed, May 20, 2009 at 01:54:24AM +0900, Mario Ruiz 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 + "</")

--
Aaron Patterson
http://tenderlovem...

Mario Ruiz

5/19/2009 5:14:00 PM

0

F. Senault wrote:
> Le 19 mai � 18:54, Mario Ruiz a �crit :
>

Yep It works!!!

Thank you very much.
--
Posted via http://www.ruby-....

Mark Thomas

5/20/2009 11:28:00 AM

0

On May 19, 12:54 pm, Mario Ruiz <tcbl...@gmail.com> 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!)