作为“String#tr”参数的字符串文字中的转义状态
对于作为 String#tr
参数的单引号字符串文字中的反斜杠的转义状态,对我来说有些神秘。你能解释一下下面三个例子之间的对比吗?我特别不明白第二个。为了避免复杂化,我在这里使用 'd'
,在双引号中转义时不会改变含义 ("\d"
= "d"< /代码>)。
'\\'.tr('\\', 'x') #=> "x"
'\\'.tr('\\d', 'x') #=> "\\"
'\\'.tr('\\\d', 'x') #=> "x"
There is something mysterious to me about the escape status of a backslash within a single quoted string literal as argument of String#tr
. Can you explain the contrast between the three examples below? I particularly do not understand the second one. To avoid complication, I am using 'd'
here, which does not change the meaning when escaped in double quotation ("\d"
= "d"
).
'\\'.tr('\\', 'x') #=> "x"
'\\'.tr('\\d', 'x') #=> "\\"
'\\'.tr('\\\d', 'x') #=> "x"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
tr
中的转义tr
的第一个参数的工作方式与正则表达式中的括号字符分组非常相似。您可以在表达式的开头使用^
来否定匹配(替换任何不匹配的内容),并使用例如af
来匹配一系列字符。由于它具有控制字符,因此它也会在内部进行转义,因此您可以使用-
和^
作为文字字符。在 Ruby 单引号字符串中转义
此外,当使用单引号时,Ruby 会尽可能包含反斜杠,即当它不用于实际转义另一个反斜杠或单引号时。
重新审视示例
考虑到所有这些,让我们再次看一下示例。
定义为
'\\'
的字符串成为文字字符串\
,因为第一个反斜杠转义了第二个反斜杠。那里没有什么惊喜。定义为
'\\d'
的字符串成为文字字符串\d
。tr
引擎又使用文字字符串中的反斜杠来转义d
。结果:tr
将d
的实例替换为 x。定义为
'\\\d'
的字符串将变为文字\\d
。第一个\\
变为\
。那么\d
就变成了\d
,即反斜杠被保留。 (这种特殊行为与双字符串不同,双字符串中的反斜杠会被活活吃掉,只留下一个孤独的d
)文字字符串
\\d
然后使tr
将所有反斜杠或d
字符替换为替换字符串。Escaping in
tr
The first argument of
tr
works much like bracket character grouping in regular expressions. You can use^
in the start of the expression to negate the matching (replace anything that doesn't match) and use e.g.a-f
to match a range of characters. Since it has control characters, it also does escaping internally, so you can use-
and^
as literal characters.Escaping in Ruby single quote strings
Furthermore, when using single quotes, Ruby tries to include the backslash when possible, i.e. when it's not used to actually escape another backslash or a single quote.
The examples revisited
With all that in mind, let's look at the examples again.
The string defined as
'\\'
becomes the literal string\
because the first backslash escapes the second. No surprises there.The string defined as
'\\d'
becomes the literal string\d
. Thetr
engine, in turn uses the backslash in the literal string to escape thed
. Result:tr
replaces instances ofd
with x.The string defined as
'\\\d'
becomes the literal\\d
. First\\
becomes\
. Then\d
becomes\d
, i.e. the backslash is preserved. (This particular behavior is different from double strings, where the backslash would be eaten alive, leaving only a lonesomed
)The literal string
\\d
then makestr
replace all characters that are either a backslash or ad
with the replacement string.