I want to insert backslash before apostrophe in "children's world" string. Is there a easy way to do it?
irb(main):035:0> s = "children's world"
=> "children's world"
irb(main):036:0> s.gsub('\'', '\\\'')
=> "childrens worlds world"
from ruby-doc.org about the replacement pattern for gsub
:
the sequences \\1, \\2, and so on may be used to interpolate successive groups in the match
This includes the sequence \\'
, which means "everything following what I matched".
Either "\\\\'"
or '\\\\\\''
will both produce \\'
(remember that \\
has to be escaped in both double and single quoted strings, and that '
has to be escaped in single-quoted strings, so using single-quotes in this case actually makes things more verbose). Eg:
puts "before*after".gsub("*", "\\'")
"beforeafterafter"
puts "before*after".gsub("*", '\\\'')
"beforeafterafter"
What you want gsub
to see then is actually \\\\'
, which can be produced by both "\\\\\\\\'"
and '\\\\\\\\\\''
. So:
puts s.gsub("'", "\\\\'")
children\'s world
puts s.gsub("'", '\\\\\'')
children\'s world
or if you have to do a lot with \\
you could take advantage of the fact that when you use /.../
(or %r{...}
) you don't have to double-escape the backslashes:
puts s.gsub("'", /\\'/.source)
children\'s world
>> puts s.gsub("'", "\\\\'")
children\'s world
Your problem is that the string "\\'" is meaningful to gsub in a replacement string. In order to make it work the way you want, you have to use the block form.
s.gsub("'") {"\\'"}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.