From: Ryan Mcdonald Date: 2007-06-21T09:49:27+09:00 Subject: Re: Do You Understand Regular Expressions? Daniel DeLorme wrote: > Axel Etzold wrote: >>> irb(main):001:0> "hello".scan(/.*/) >>> => ["hello", ""] >>> >>> I was expecting one match, not two, because .* matches everything, >>> right? Can someone explain why an empty string is also matched? >> >> String.scan searches for all occurrences of (any number of any >> character) here. So zero occurrences is one match. > > That doesn't really explain why the regexp finds an extra empty string. > I know that zero occurrences is one match but after a greedy match that > matches everything, there should be (logically?) no other match. I am no > stranger to regexps and the result is counter-intuitive to me; I would > consider it a bug. Or at least a very very peculiar behavior. > > Daniel I agree. Can someone explain why gsub, sub or scan matches with * are different than =~ matches with * puts "hello".gsub(/[aeiou]/, '<\1>') # h<>ll<> puts "hello".gsub(/.*/, '<\1>') # <><> print "before: #{$`}\n" # before: hello print "match: #{$&}\n" # match: print "after: #{$'}\n" # after: puts "hello" =~ (/.*/) # 0 print "before: #{$`}\n" # before: print "match: #{$&}\n" # match: hello print "after: #{$'}\n" # after: thanks! -- Posted via http://www.ruby-forum.com/.