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 ' 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
Hi,
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
路路路
On Apr 30, 12:22 pm, theist...@gmail.com wrote:
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/thread/d8f4
74e7f2959585/9cadabc099a27925?lnk=st&q=#9cadabc099a27925>
m.
路路路
<theistian@gmail.com> wrote:
irb(main):003:0> sst = st.gsub(/'/,"\'")
--
matt neuburg, phd = matt@tidbits.com, Matt Neuburg鈥檚 Home Page
Leopard - http://www.takecontrolbooks.com/leopard-customizing.html
AppleScript - http://www.amazon.com/gp/product/0596102119
Read TidBITS! It's free and smart. http://www.tidbits.com