简体   繁体   中英

Escaping ruby string

I have a string with two single quotes. ie "lady's lady's"

I want to escape the quotes so I get: "lady\\'s lady\\'s".

I have tried the following:

> "lady's lady's".gsub("'", "\\'")
 => "ladys lady'ss ladyss" 

> "lady's lady's".gsub("'", "\\\\'")
 => "lady\\'s lady\\'s" 

> "lady's lady's".gsub("'", "\'")
 => "lady's lady's" 

Any help?

Classically, the characters that need to be escaped are the non-alphanumerics. Perl's quotemeta , for instance, escape everything that isn't a number, a letter, or an underscore.

You can replicate this behaviour by using gsub :

str = "lady's lady's"

puts str.gsub(/(?=\W)/, '\\')

output

lady\'s\ lady\'s

If you particularly don't want anything but the apostrophes escaping then the regex is simple to change, replacing (?=\\W) with (?=') .


Note

The result

> "lady's lady's".gsub("'", "\\'")
 => "ladys lady'ss ladyss" 

is because using a literal replacement string of «\\'» replaces each apostrophe with the value of the global variable $' - the string after the match.

So the first apostrophe is replaced with «s lady's» and the second with «s» , resulting in the bizarre «ladys lady'ss ladyss» .

You have to use a literal replacement string of «\\\\'» to replace with just «\\'»

It's much neater to use a look-ahead and avoid having to replace the apostrophe:

> puts "lady's lady's".gsub(/(?=')/, '\\')
lady\'s lady\'s
=> nil
"lady's lady's".gsub("'", "\\\\'") # => "lady\\'s lady\\'s"

As @Neil mentioned see below :

"lady's lady's".gsub(/'/, "\\\\\'").chars.to_a 
# => ["l",
#     "a",
#     "d",
#     "y",
#     "\\",
#     "'",
#     "s",
#     " ",
#     "l",
#     "a",
#     "d",
#     "y",
#     "\\",
#     "'",
#     "s"]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM