Ruby 中奇怪的反斜杠替换 [英] Weird backslash substitution in Ruby

查看:69
本文介绍了Ruby 中奇怪的反斜杠替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看不懂这段 Ruby 代码:

I don't understand this Ruby code:

>> puts '\\ <- single backslash'
# \ <- single backslash

>> puts '\\ <- 2x a, because 2 backslashes get replaced'.sub(/\\/, 'aa')
# aa <- 2x a, because two backslashes get replaced

到目前为止,一切都在预料之中.但是如果我们用 /\\/ 搜索 1,并用 '\\\\' 编码的 2 替换,为什么我们会得到这个:

so far, all as expected. but if we search for 1 with /\\/, and replace with 2, encoded by '\\\\', why do we get this:

>> puts '\\ <- only 1 ... replace 1 with 2'.sub(/\\/, '\\\\')
# \ <- only 1 backslash, even though we replace 1 with 2

然后,当我们用 '\\\\\\' 编码 3 时,我们只得到 2:

and then, when we encode 3 with '\\\\\\', we only get 2:

>> puts '\\ <- only 2 ... 1 with 3'.sub(/\\/, '\\\\\\')
# \\ <- 2 backslashes, even though we replace 1 with 3

任何人都能够理解为什么在替换字符串中会吞下反斜杠?这发生在 1.8 和 1.9 上.

anyone able to understand why a backslash gets swallowed in the replacement string? this happens on 1.8 and 1.9.

推荐答案

这是一个问题,因为反斜杠 (\) 用作正则表达式和字符串的转义字符.您可以使用特殊变量 \&减少 gsub 替换字符串中的反斜杠数量.

This is an issue because backslash (\) serves as an escape character for Regexps and Strings. You could do use the special variable \& to reduce the number backslashes in the gsub replacement string.

foo.gsub(/\\/,'\&\&\&') #for some string foo replace each \ with \\\

我应该提到 \& 的值来自正则表达式匹配,在这种情况下是单个反斜杠.

I should mention that the value of \& is from a Regexp match, in this case a single backslash.

另外,我认为有一种特殊的方法可以创建一个禁用转义字符的字符串,但显然不是.这些都不会产生两个斜杠:

Also, I thought that there was a special way to create a string that disabled the escape character, but apparently not. None of these will produce two slashes:

puts "\\"
puts '\\'
puts %q{\\}
puts %Q{\\}
puts """\\"""
puts '''\\'''
puts <<EOF
\\
EOF  

这篇关于Ruby 中奇怪的反斜杠替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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