开发者

Inserting Escape Characters

开发者 https://www.devze.com 2022-12-09 18:23 出处:网络
I want to replace and insert escape character sequences with their escape character values, also taking into account that \'\\\' nullifies the escape character.

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

精彩评论

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