Regex.escape bug

T

Tasos Laskos

Hi guys,

I'm using "ruby 1.9.1p378 (2010-01-10 revision 26273) [x86_64-linux]"
and just noticed a possible bug in Regex.escape() while using it with
gsub()


This:
--------
pp Regexp.escape( '.rb' )
--------

yields:
--------
"\\.rb"
--------

while it should be "\.rb".

Regexp.new( '.rb' ) or Regexp.new( '\.rb' ) work though, they replaces
the ".rb" string as expected.
Yes I know that "Regexp.new( '.rb' )" works incidentally but I'm just
mentioning it. :)
 
J

Joel VanderWerf

Tasos said:
Hi guys,

I'm using "ruby 1.9.1p378 (2010-01-10 revision 26273) [x86_64-linux]"
and just noticed a possible bug in Regex.escape() while using it with
gsub()


This:
--------
pp Regexp.escape( '.rb' )
--------

yields:
--------
"\\.rb"
--------

while it should be "\.rb".

Regexp.new( '.rb' ) or Regexp.new( '\.rb' ) work though, they replaces
the ".rb" string as expected.
Yes I know that "Regexp.new( '.rb' )" works incidentally but I'm just
mentioning it. :)

It is correct, because it lets you do this:
=> nil

Note that "\\.rb" is the same string as '\.rb'.
 
R

Robert Klemme

Hi guys,

I'm using "ruby 1.9.1p378 (2010-01-10 revision 26273) [x86_64-linux]"
and just noticed a possible bug in Regex.escape() while using it with
gsub()


This:

No, it should be as it is as Joel explained. Note also

irb(main):007:0> puts Regexp.escape( '.rb' )
\.rb

It is the representation of the string that includes a backslash to
properly escape the backslash:

irb(main):010:0> "\\n".size
=> 2
irb(main):011:0> "\n".size
=> 1
irb(main):012:0> puts "\\n"
\n
=> nil
irb(main):013:0> puts "\n"

=> nil

Regexp.new( '.rb' ) or Regexp.new( '\.rb' ) work though, they replaces
the ".rb" string as expected.
Yes I know that "Regexp.new( '.rb' )" works incidentally but I'm just
mentioning it. :)

It works but it does not match the sequence ".rb" - rather it matches
any character followed by "rb":

irb(main):004:0> r = Regexp.new( '.rb' )
=> /.rb/
irb(main):005:0> r.match '.rb'
=> #<MatchData ".rb">
irb(main):006:0> r.match 'oooopsrb'
=> #<MatchData "srb">

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top