[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

n00b string replace

theistian

4/30/2008 11:22:00 AM

Hi I'm triying to substitute any ocurrences of ' in a string by \'

Here's a bit of testing I made in irb which wtf's me:

irb(main):002:0> st = "un ' monton ' de ' apostrofes '"
=> "un ' monton ' de ' apostrofes '"
irb(main):003:0> sst = st.gsub(/'/,"\'")
=> "un ' monton ' de ' apostrofes '"

ok substitute ' by ' :P I don't know why interpeter interpret \' as
' when in a double-quoted string contex but I'm a newbie so sure I'm
wrong

irb(main):004:0> sst = st.gsub(/'/,"\\'")
=> "un monton ' de ' apostrofes ' monton de ' apostrofes ' de
apostrofes ' apostrofes "
irb(main):005:0> sst = st.gsub(/'/,"\\\'")
=> "un monton ' de ' apostrofes ' monton de ' apostrofes ' de
apostrofes ' apostrofes "

This seems to be substitute ' by "rest of string from ocurrence"
regardless of scape chars

Totally dazzed and desperate I tried with another backslash.... who
cares ... and get this

irb(main):006:0> sst = st.gsub(/'/,"\\\\'")
=> "un \\' monton \\' de \\' apostrofes \\'"

How do I get "un \' monton \' de \' apostrofes \'" from "un ' monton '
de ' apostrofes '"? using regex?

Thanks
2 Answers

evans.jon@gmail.com

4/30/2008 1:08:00 PM

0

Hi,

On Apr 30, 12:22 pm, theist...@gmail.com wrote:

> How do I get "un \' monton \' de \' apostrofes \'" from "un ' monton '
> de ' apostrofes '"? using regex?

Like this:

>> st = "un ' monton ' de ' apostrofes '"
=> "un ' monton ' de ' apostrofes '"
>> st.gsub(/'/, "\\\\'")
=> "un \\' monton \\' de \\' apostrofes \\'"

It just displays with \\ in there because it needs to escape the itself when displaying it. Any manipulations you need to do on the
actual string object will only see a single '\' character rather than
a double.

>> s = "'"
=> "'"
>> s.gsub!(/'/, "\\\\'")
=> "\\'"
>> s.length
=> 2
>> s[0].chr
=> "\\"
>> s[1].chr
=> "'"

Jon

matt

5/3/2008 3:32:00 PM

0

<theistian@gmail.com> wrote:

> irb(main):003:0> sst = st.gsub(/'/,"\'")

You can really confuse the heck out of yourself this way. There are two
problems:

(1) Backslashes must be escaped in a double-quoted string.

(2) gsub has special behavior unlike anything else in Ruby: backslashes
are unescaped in the second parameter, regardless of the quoting.

So, if you want one backslash to be substituted, and if you insist on
double-quoting, you have to type *four* backslashes:

irb(main):003:0> puts "hello".gsub("e","\\\\")
h\llo

For the workaround, check this recent thread:

<http://groups.google.com/group/comp.lang.ruby/browse_thread/t...
74e7f2959585/9cadabc099a27925?lnk=st&q=#9cadabc099a27925>

m.
--
matt neuburg, phd = matt@tidbits.com, http://www.tidbits...
Leopard - http://www.takecontrolbooks.com/leopard-custom...
AppleScript - http://www.amazon.com/gp/product/...
Read TidBITS! It's free and smart. http://www.t...