开发者

Replace ' with \' in Ruby?

I'm trying to figure out how to replace a quote like ' with something like \'.

How would开发者_如何学运维 I do this?

I have tried

"'".gsub("'","\\'")

but it just gives an empty string. What am I doing wrong here?


How about this

puts "'".gsub("'","\\\\'")
\'

The reason is that \' means post-match in gsub (regex) and because of that it needs to be escaped with \\' and \ is obviously escaped as \\, ending up with \\\\'.

Example

>> "abcd".gsub("a","\\'")
=> "bcdbcd"

a is replaced with everything after a.


The $' variable is the string to the right of the match. In the gsub replacement string, the same variable would be \' -- hence the problem.

x = "'foo'"
x.gsub!(/'/, "\\'")
puts x.inspect        # foo'foo

This should work:

x = "'foo'"
x.gsub!(/'/, "\\\\'")
puts x.inspect
puts x


That might be a bug.. Or at the very least, something which breaks MY idea of the principle of least surprise.

irb(main):039:0> "life's grand".gsub "'", "\\\'"
=> "lifes grands grand"
irb(main):040:0> "life's grand".gsub "'", "\\\\'"
=> "life\\'s grand"


A two-step approach I've actually used...

BACKSLASH = 92.chr
temp = "'".gsub("'", "¤'")
puts temp.gsub("¤", BACKSLASH)
=> "\'"

Will only work if '¤' isn't used in the text obviously...


How about doing this :

"'".gsub("\\","\\\\\\\\").gsub("'","\\\\'")

Not pretty but I think it works...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜