插入转义字符

我想用它们的转义字符值替换和插入转义字符序列,同时考虑到’\’使转义字符无效。

例如

"This is a \n test. Here is a \\n which represents a newline" 

在Ruby中实现这一目标的最简单方法是什么?

我假设你正在努力解决以下问题:

 "\\n".gsub(/\\\\/, "\\").gsub(/\\n/, "\n") # => "n" "\\n".gsub(/\\n/, "\n").gsub(/\\\\/, "\\") # => "\\\n" 

String#gsub可以使用一个块参数来执行替换。

 str.gsub(/\\(.)/) do |s| case $1 when "n" "\n" when "t" "\t" else $1 end end 

这样就不会首先替换特殊的转义序列,一切都按照已经过的方式运行。

你想要与此相反吗?

 puts "This is a \n test. Here is a \\n which represents a newline" 

=>

这是一个
 测试。 这是\ n,它代表换行符