为什么 String#gsub 的内容加倍?
s = "#main= 'quotes'
s.gsub "'", "\\'" # => "#main= quotes'quotes"
这似乎是错误的,我希望
当我不使用转义字符时得到 "#main= \\'quotes\\'"
,然后它按预期工作。
s.gsub "'", "*" # => "#main= *quotes*"
所以,逃跑一定是有什么关系。
使用 ruby 1.9.2p290
我需要用反斜杠和引号替换单引号。
甚至更多的矛盾:
"\\'".length # => 2
"\\*".length # => 2
# As expected
"'".gsub("'", "\\*").length # => 2
"'a'".gsub("'", "\\*") # => "\\*a\\*" (length==5)
# WTF next:
"'".gsub("'", "\\'").length # => 0
# Doubling the content?
"'a'".gsub("'", "\\'") # => "a'a" (length==3)
这里发生了什么?
s = "#main= 'quotes'
s.gsub "'", "\\'" # => "#main= quotes'quotes"
This seems to be wrong, I expect to get "#main= \\'quotes\\'"
when I don't use escape char, then it works as expected.
s.gsub "'", "*" # => "#main= *quotes*"
So there must be something to do with escaping.
Using ruby 1.9.2p290
I need to replace single quotes with back-slash and a quote.
Even more inconsistencies:
"\\'".length # => 2
"\\*".length # => 2
# As expected
"'".gsub("'", "\\*").length # => 2
"'a'".gsub("'", "\\*") # => "\\*a\\*" (length==5)
# WTF next:
"'".gsub("'", "\\'").length # => 0
# Doubling the content?
"'a'".gsub("'", "\\'") # => "a'a" (length==3)
What is going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您会被
\' 在正则表达式替换字符串内
:
因此,当您说
"\\'"
时,双\\
就变成了一个反斜杠,结果是\'
但这意味着“最后一次成功匹配右侧的字符串。”如果您想用转义单引号替换单引号,则需要转义更多内容以克服\'
的特殊性:或者避免使用牙签并使用块形式:
如果你试图转义反引号、加号、甚至单个数字。
这里的总体教训是更喜欢 gsub 的块形式 除了最琐碎的替换之外的任何内容。
You're getting tripped up by the specialness of
\'
inside a regular expression replacement string:So when you say
"\\'"
, the double\\
becomes just a single backslash and the result is\'
but that means "The string to the right of the last successful match." If you want to replace single quotes with escaped single quotes, you need to escape more to get past the specialness of\'
:Or avoid the toothpicks and use the block form:
You would run into similar issues if you were trying to escape backticks, a plus sign, or even a single digit.
The overall lesson here is to prefer the block form of
gsub
for anything but the most trivial of substitutions.由于
\
它与\\
等效,如果您想获得双反斜杠,则必须输入四个反斜杠。Since
\
it's\\
equivalent if you want to get a double backslash you have to put four of ones.您还需要转义 \:
输出
在外部论坛上找到了一个很好的解释:
来源
You need to escape the \ as well:
Outputs
A good explanation found on an outside forum:
source