gpt4 book ai didi

ruby - Ruby 中 gsub 的奇怪行为

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:46 25 4
gpt4 key购买 nike

puts 'the\t\'arget'.gsub("'", "\\'")

产生以下输出:

the\targetarget

为什么?

最佳答案

gsub 替换中的 \\' 实际上是一个反向引用,即将 ' 字符替换为 ' 字符之后的所有内容在原始字符串中,即 arget

这是来自 ruby docs on String#gsub 的引述:

If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern’s capture groups of the form \\d, where d is a group number, or \\k, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as &$, will not refer to the current match.

关于ruby - Ruby 中 gsub 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15681109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com