插入转义字符

时间:2009-10-31 01:07:01

标签: ruby string

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

例如

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

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

2 个答案:

答案 0 :(得分:1)

我认为你正在努力解决以下问题:

"\\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

这样,首先不会替换任何特殊的转义序列,并且所有转义都可以解决。

答案 1 :(得分:0)

你想要与此相反吗?

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

=>

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