我正在从一个包含以下序列的文件中加载文本:
abc\ndef\tghi
我希望能够“取消转义”所有特殊字符,例如将\n
视为换行符,\t
视为制表符等,而不是自动地以\\n
或\\t
的形式出现在字符串中。
有没有简单的方法可以做到这一点?
文本将按文件中的内容加载。 如果文件中有字面文本\和n而不是换行符,则将加载此内容。 如果您想更改已知的一组转义字符,可以简单地使用gsub
替换它们。
line='abc\ndef\tghi'
line.gsub!('\n', "\n")
line.gsub!('\t', "\t")
def unescape(string)
dup = string.dup
escaped_chars = ['n', 't', 'r', 'f', 'v', '0', 'a']
escaped_subs = {
"n" => "\n",
"t" => "\t",
"r" => "\r",
"f" => "\f",
"v" => "\v",
"0" => "\0",
"a" => "\a"
}
pos = 0
while pos < dup.length
if dup[pos] == '\\' and escaped_chars.include? dup[pos + 1]
dup[pos..(pos + 1)] = escaped_subs[dup[pos + 1]]
end
pos += 1
end
return dup
end
YAML.unescape 怎么样?
require 'syck/encoding'
require 'yaml'
YAML.unescape("\\n")