使用单引号而不是双引号时转义是有限的:
puts 'sinlge\nquote'
puts "double\nquote"
"\0"
是空字符(即在 C 中用于确定字符串的结尾),其中 as'\0'
是"\\0"
,因此两者都是'hello'.gsub(/.+/, '\0')
和'hello'.gsub(/.+/, "\\0")
return "hello"
,但'hello'.gsub(/.+/, "\0")
返回"\000"
。现在'hello'.gsub(/.+/, '\\0')
返回'hello'
的是 ruby 试图处理没有记住单引号和双引号之间的区别的程序员。gsub
实际上,这与:'\0' == "\\0"
和.无关'\\0' == "\\0"
。按照这个逻辑,不管你怎么想,这就是 ruby 看到其他字符串的方式: both'\\\0'
和'\\\\0'
equal "\\\\0"
,它(打印时)给你\\0
. 由于 gsub\x
用于插入匹配号 x,您需要一种方法来转义\x
,即\\x
,或在其字符串表示中:"\\\\x"
。
因此线
puts 'hello'.gsub(/.+/, "\\0 \\\\0 \\\\\\0 \\\\\\\\0")
确实导致
hello \0 \hello \\0