用 \'X 字符串替换时出现奇怪的 Ruby 行为
Strange Ruby behavior when replacing with \'X string
我正在生成一些 RTF 字符串并需要 \'bd 代码。我在使用 sub 和 gsub 命令时遇到问题。
puts 'abc'.sub('a',"\'B") => "bcBbc"
语句将目标替换为不带\'的'B',并将字符串的剩余部分复制到前面。我尝试了很多变体,问题似乎出在 \' 本身。
我有办法解决这个问题,但我想知道我是否做错了根本性的事情,或者这是否是 Ruby 的怪癖。
谢谢
Similarly, \&
, \'
, \`
, and \+
correspond to special variables, $&
, $'
, $`
, and $+
, respectively.
和here,文档接着说:
$~
is equivalent to ::last_match;
$&
contains the complete matched text;
$`
contains string before match;
$'
contains string after match;
</code>, <code>
and so on contain text matching first, second, etc capture group;
$+
contains last capture group.
Example:
m = /s(\w{2}).*(c)/.match('haystack') #=> #<MatchData "stac" 1:"ta" 2:"c">
$~ #=> #<MatchData "stac" 1:"ta" 2:"c">
Regexp.last_match #=> #<MatchData "stac" 1:"ta" 2:"c">
$& #=> "stac"
# same as m[0]
$` #=> "hay"
# same as m.pre_match
$' #=> "k"
# same as m.post_match
#=> "ta"
# same as m[1]
#=> "c"
# same as m[2]
#=> nil
# no third group in pattern
$+ #=> "c"
# same as m[-1]
所以,\'
在替换字符串中有特殊的意义。这意味着 "The portion of the original string after the match" - 在这种情况下,它是 "bc"
.
所以你得到的不是\'Bbc
,而是bcBbc
因此,不幸的是,在这种奇怪的情况下,您需要 double-转义反斜杠:
puts 'abc'.sub('a',"\\'B") => "\'Bbc"
我正在生成一些 RTF 字符串并需要 \'bd 代码。我在使用 sub 和 gsub 命令时遇到问题。
puts 'abc'.sub('a',"\'B") => "bcBbc"
语句将目标替换为不带\'的'B',并将字符串的剩余部分复制到前面。我尝试了很多变体,问题似乎出在 \' 本身。
我有办法解决这个问题,但我想知道我是否做错了根本性的事情,或者这是否是 Ruby 的怪癖。
谢谢
Similarly,
\&
,\'
,\`
, and\+
correspond to special variables,$&
,$'
,$`
, and$+
, respectively.
和here,文档接着说:
$~
is equivalent to ::last_match;$&
contains the complete matched text;$`
contains string before match;$'
contains string after match;</code>, <code>
and so on contain text matching first, second, etc capture group;$+
contains last capture group.Example:
m = /s(\w{2}).*(c)/.match('haystack') #=> #<MatchData "stac" 1:"ta" 2:"c"> $~ #=> #<MatchData "stac" 1:"ta" 2:"c"> Regexp.last_match #=> #<MatchData "stac" 1:"ta" 2:"c"> $& #=> "stac" # same as m[0] $` #=> "hay" # same as m.pre_match $' #=> "k" # same as m.post_match #=> "ta" # same as m[1] #=> "c" # same as m[2] #=> nil # no third group in pattern $+ #=> "c" # same as m[-1]
所以,\'
在替换字符串中有特殊的意义。这意味着 "The portion of the original string after the match" - 在这种情况下,它是 "bc"
.
所以你得到的不是\'Bbc
,而是bcBbc
因此,不幸的是,在这种奇怪的情况下,您需要 double-转义反斜杠:
puts 'abc'.sub('a',"\\'B") => "\'Bbc"