Bug #8512
closed
- Status changed from Open to Rejected
This is due to Regexp replace syntax and literal strings.
In literal strings, you need two \ to produce one \ character (a single is the start of an escape character like \t, \n, ...).
And in Regexp replacement strings, you need to escape the \ (a single one is the beginning of a special replacement sequence like \1,&,...).
So that makes 4 \ for one produced in literal replacement strings:
"\".gsub("\", "\\").length
=> 1
"\".gsub("\", "\\\\").length
=> "\\"
Not so nice, but definitely expected behavior.
This should be documented in Regexp's overview though.
=begin
the docs says:
((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.))
so you need more "" in your string
=end
Hanmac (Hans Mackowiak) wrote:
=begin
the docs says:
((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.))
so you need more "" in your string
=end
Thanks for the explanation.
For the record, you can also use the hash or block replacement forms, because those doesn't use regexp back-references:
"\".gsub("\", "\"=>"\\") #=> "\\"
"\".gsub("\") { "\\" } #=> "\\"
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0