regex trick

A

Alain FELER

I want to replace all ' by \' ? (I need it to do inserts in mysql).
s = "j'ai"
s.gsub!(/'/,'\'')
p s ==> gives j'ai and not j\'ai as I want
Thanks for help.
 
M

Mike Stok

I want to replace all ' by \' ? (I need it to do inserts in mysql).
Thanks for help.

What interface to MySQL are you using? I know that the Ruby DBI
module allows you to use place-holders in queries, and the DBI layer
does the escaping for you e.g.

dbh.do("INSERT INTO people (id, name, height) VALUES(?, ?, ?)",
nil, "Na'il", 76)

The resulting statement produced by do and sent to the server looks
like this:

INSERT INTO people (id,name,height) VALUES(NULL,'Na\'il',76)

(stolen from http://www.kitebird.com/articles/ruby-dbi.html) or if
you are using the ruby mysql interface then (from http://
www.kitebird.com/articles/ruby-mysql.html)

Using escape_string, the platypus record might be inserted as
follows:

name = dbh.escape_string("platypus")
category = dbh.escape_string("don't know")
dbh.query("INSERT INTO animal (name, category)
VALUES ('" + name + "','" + category + "')")

Hope this helps,

Mike

--

Mike Stok <[email protected]>
http://www.stok.co.uk/~mike/

The "`Stok' disclaimers" apply.
 
A

Alain FELER

Thank you very much for these four answers, but curiously none works on
my box ! :
Stefan Lang : s.gsub!("'", "\\\\'") gives "j\\'ai" not "j\'ai"
Timothy Hunter : s.sub(/'/) { '\\\'' } gives "j\\'ai"
you : s.gsub!(/'/, "\\\\'") gives "j\\'ai"
and : s.gsub!(/'/) { "\\'" } gives "j'ai"
(I am using ruby 1.8.2.14 on Windows 2000 configured in french,
and I can't even type the {} characters in irb, but I tried with Scite)
However the ruby mysql interface escape_string method works fine.
Thank you.
AF

Mike Stok a écrit :
 
E

Eric Hodel

Thank you very much for these four answers, but curiously none
works on my box ! :

Incorrect. They all work.

p "j\\'ai"
"j\\'ai"
puts "j\\'ai"
j\'ai
Stefan Lang : s.gsub!("'", "\\\\'") gives "j\\'ai" not "j\'ai"

puts "j'ai".gsub("'", "\\\\'")
j\'ai
Timothy Hunter : s.sub(/'/) { '\\\'' } gives "j\\'ai"

puts "j'ai".gsub(/'/) { '\\\'' }
j\'ai
you : s.gsub!(/'/, "\\\\'") gives "j\\'ai"

puts "j'ai".gsub(/'/, "\\\\'")
j\'ai
and : s.gsub!(/'/) { "\\'" } gives "j'ai"

puts "j'ai".gsub(/'/) { "\\'" }
j\'ai
 
A

Alain FELER

Well, sorry:
p s gives "j\\'ai"
puts s gives j\'ai
print s gives j\'ai
so every four methods work if the result is properly printed
AF

Alain FELER a écrit :
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top