Actions
Bug #14791
closedString.sub wrong parsing of replacement with capturing group
Status:
Rejected
Assignee:
-
Target version:
-
ruby -v:
ruby 2.3.3p222 (2016-11-21) [x86_64-linux-gnu]
Description
irb(main):001:0> "abc".sub(/(b)/, '#\1#') # works
=> "a#b#c"
irb(main):002:0> "abc".sub(/(b)/, '\\1') # doesn't works, should be "a\bc"
=> "abc"
irb(main):003:0> "abc".sub(/(b)/, '\\\1') # doesn't works, should be "a\\bc"
=> "a\\1c"
irb(main):004:0> "abc".sub(/(b)/, "\\1") # works
=> "abc"
irb(main):005:0> "abc".sub(/(b)/, "\\\\1") # doesn't works, should be "a\bc"
=> "a\\1c"
irb(main):006:0> "abc".sub(/(b)/, '\ \1') # works
=> "a\ bc"
Updated by Hanmac (Hans Mackowiak) almost 6 years ago
read the Docs:
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<n>", where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash.
it is explained what to do with the blackslashes. and how much do you need.
Updated by churib (Timo Grodzinski) almost 6 years ago
Can you give a solution for my second example?
"abc".sub(/(b)/, '\\1') # doesn't works, should be "a\bc"
I want to replace the 'b' with '\b'. How many backslashes do I need?
The #sub method has problems with consecutive backslashes in combination with backreferences.
Updated by Hanmac (Hans Mackowiak) almost 6 years ago
need 5 or 6 (6 when using ")
"abc".sub(/(b)/, '\\\\\1') #=> "a\\bc"
"abc".sub(/(b)/, "\\\\\1") #=> "a\\\x01c"
"abc".sub(/(b)/, "\\\\\\1") #=> "a\\bc"
but be careful that irb returns inspected value, that is important if you want to see \ or \ stuff
puts "abc".sub(/(b)/, '\\\\\1') #=> a\bc
p "abc".sub(/(b)/, '\\\\\1') #=> a\\bc
Updated by shyouhei (Shyouhei Urabe) almost 6 years ago
- Status changed from Open to Rejected
Let me reject; this is not a bug.
Updated by churib (Timo Grodzinski) almost 6 years ago
Thanks for help!
I don't unterstand, why five backslahes are required in single quotes. My understanding was that characters in single quotes won't get interpolated so two backslashes should be sufficient.
Actions
Like0
Like0Like0Like0Like0Like0