Inserting Escape Characters

后端 未结 2 454
轻奢々
轻奢々 2021-01-23 22:40

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

For exam

相关标签:
2条回答
  • 2021-01-23 22:53

    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.

    0 讨论(0)
  • 2021-01-23 23:03

    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 讨论(0)
提交回复
热议问题