我想在“children's world”字符串中的撇号前插入反斜杠。有简单的方法吗?
irb(main):035:0> s = "children's world"
=> "children's world"
irb(main):036:0> s.gsub('\'', '\\\'')
=> "childrens worlds world"
最佳答案
回答
你需要一些额外的反斜杠:
>> puts "children's world".gsub("'", '\\\\\'')
children\'s world
或更简洁一些(因为您不需要在双引号字符串中转义 '
):
>> puts "children's world".gsub("'", "\\\\'")
children\'s world
或者更简洁:
>> puts "children's world".gsub("'") { "\\'" }
children\'s world
解释
你的 '\\\''
生成 \'
作为一个字符串:
>> puts '\\\''
\'
和\'
是 Ruby 中的一种特殊替换模式。来自 ruby-doc.org :
you may refer to some special match variables using these combinations ...
\'
corresponds to$'
, which contains string after match
所以 \'
那gsub
在第二个参数中看到被解释为特殊模式(匹配后原始字符串中的所有内容)而不是文字 \'
.
所以你想要什么gsub
看到其实是\\'
, 可以由 '\\\\\''
生产或 "\\\\'"
.
或者,如果您使用 gsub
的 block 形式( gsub("xxx") { "yyy" }
) 然后 Ruby 接受替换字符串 "yyy"
从字面上看,无需尝试应用替换模式。
注意:如果您必须创建一个包含大量 \
的替换字符串当您使用 /.../
时,您可以利用这一事实(或 %r{...}
)你不必两次转义反斜杠:
>> puts "children's world".gsub("'", /\\'/.source)
children\'s world
或者您可以使用单引号 heredoc:(使用 <<'STR'
而不仅仅是 <<STR
)
>> puts "children's world".gsub("'", <<'STR'.strip)
\\'
STR
children\'s world
关于ruby - 如何将单个反斜杠字符添加到 Ruby 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/716767/