From: Robert Klemme Date: 2008-05-18T20:50:06+09:00 Subject: Re: sub/gsub bug? On 18.05.2008 13:38, Robert Klemme wrote: > On 18.05.2008 06:33, Phlip wrote: >> Matt wrote: >> >>> Is this a bug? >>> >>> irb(main):032:0> "matt's test".sub(/'/, "\\'") >>> => "matts tests test" >>> >>> It's trying to replace a single quote with an escaped quote. >> >> To understand the bug, try this: > > There is no bug. > >> irb(main):009:0> "matt's test".sub(/(')/, '\1') >> => "matt's test" >> >> The 'single ticks' interpret \1 as a literal \ and a 1, not an escape. >> Then .sub sees the \1, and replaces it with the 1nth (grouping) from >> the Regexp - which is a literal tick '. >> >> Now try it with "double quotes": >> >> irb(main):005:0> "matt's test".sub(/(')/, "\\1") >> => "matt's test" >> >> The " forces us to escape the \ as \\ to get a literal \. > > And a literal \ in a replacement string is a meta character. To get a > literal in a replacement, you need \\ in the string and consequently > \\\\ in a double quoted string. > >> So your \\' indeed goes in as a literal \'. But the group replacer >> still sees a \, and snarfs it, expecting a number after it. I would >> call that a bug (essentially because I might personally be capable of >> correctly parsing a \1!) > > No, this is not a bug and it is not the "group replacer". The > replacement string is parsed by the regexp engine and since the > backslash does not escape a character that has meta capabilities (such > as & and 1..9) it is silently discarded. ^^^^^^^^^^^^^^^^^^ This was wrong of course as Matt demonstrated irb(main):019:0> "abc".gsub(/b/, "<\\'>") => "ac" But the backslash is just retained if it does not appear with a meta capable character: irb(main):020:0> "abc".gsub(/b/, "<\\a>") => "a<\\a>c" irb(main):021:0> puts "abc".gsub(/b/, "<\\a>") a<\a>c => nil Sorry, for the added confusion. Kind regards robert