为什么我的结果和两个不同?
test_string = "C:/Program Files/TestPro/TestPro Automation Framework/"
puts test_string.gsub("/","\\\\")
#result is : C:\Program Files\TestPro\TestPro Automation Framework\
puts
puts test_string.gsub("/","\\\\") .inspect
#result as desired : C:\\Program Files\\TestPro\\TestPro Automation Framework\\
最佳答案
ruby的String.inspect转义所有特殊字符,这就是为什么用.inspect看到“\\
”
参见此处的String.inspectsource
if (c == '"'|| c == '\\' ||
(c == '#' &&
p < pend &&
MBCLEN_CHARFOUND_P(rb_enc_precise_mbclen(p,pend,enc)) &&
(cc = rb_enc_codepoint(p,pend,enc),
(cc == '$' || cc == '@' || cc == '{')))) {
if (p - n > prev) str_buf_cat(result, prev, p - n - prev);
str_buf_cat2(result, "\\");
prev = p - n;
continue;
}
基本上,
if c == '\'
,将“\
”连接到它,所以它变成了“\\
”如果要对反斜杠进行双转义,则需要尝试
test_string = "C:/Program Files/TestPro/TestPro Automation Framework/"
puts test_string.gsub("/","\\\\\\\\")
#C:\\Program Files\\TestPro\\TestPro Automation Framework\\