插入转义字符 [英] Inserting Escape Characters

查看:52
本文介绍了插入转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如

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

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

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 可以接受一个块参数,它执行替换.

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.

这篇关于插入转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆