如何将单个反斜杠字符添加到 Ruby 中的字符串? [英] How to add a single backslash character to a string in Ruby?
问题描述
我想在儿童世界"字符串中的撇号前插入反斜杠.有没有简单的方法?
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 关于 gsub
的替换模式:
from ruby-doc.org about the replacement pattern for gsub
:
序列\1、\2 等可用于插入匹配中的连续组
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). E.g.:
puts "before*after".gsub("*", "\\'")
"beforeafterafter"
puts "before*after".gsub("*", '\\\'')
"beforeafterafter"
你想让 gsub
看到的实际上是 \\'
,它可以由 "\\\\'"
产生和 '\\\\''
.所以:
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
或者如果你必须用 \
做很多事情,你可以利用这样一个事实,当你使用 /.../
(或 %r{...}
) 你不必双重转义反斜杠:
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
这篇关于如何将单个反斜杠字符添加到 Ruby 中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!