开发者

Inserting Escape Characters

I want to replace and insert escape character sequences with their escape character values, also taking into account that '\' nullifies the escape character.

For example

"This is a \n test. Here is a \\n which represen开发者_开发知识库ts a newline"

What is the easiest way to achieve this in Ruby?


I assume you are reffering to the following problem:

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

String#gsub can take a block argument, which performs the substitution.

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

This way no special escape sequence is substituted first and everything works as expeted.


You want the opposite of this?

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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜