【发布时间】:2010-12-05 06:14:59
【问题描述】:
我不明白这段 Ruby 代码:
>> 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替换,为什么会得到这个:
>> puts '\\ <- only 1 ... replace 1 with 2'.sub(/\\/, '\\\\')
# \ <- only 1 backslash, even though we replace 1 with 2
然后,当我们用'\\\\\\' 编码 3 时,我们只得到 2:
>> puts '\\ <- only 2 ... 1 with 3'.sub(/\\/, '\\\\\\')
# \\ <- 2 backslashes, even though we replace 1 with 3
谁能理解为什么反斜杠会被替换字符串吞没?这发生在 1.8 和 1.9 上。
【问题讨论】: