From: ajalkane Date: 2007-06-22T03:20:04+09:00 Subject: Re: Do You Understand Regular Expressions? On Jun 21, 2:16 am, 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. At face value it is a surprising result, but upon a bit of consideration not illogical or faulty. The scan pattern finds first with greedy matching the "hello" string. As you've said, after that there is nothing to match anymore. But the pattern "/.*/" is a valid match on nothing also, as * is zero or more occurances. For example: irb(main):018:0> "hello".scan(/.*/) => ["hello", ""] irb(main):019:0> "".scan(/.*/) => [""] Compare this to using '+' which specifies there must be zero or more occurances: irb(main):020:0> "hello".scan(/.+/) => ["hello"] irb(main):021:0> "".scan(/.+/) => [] That's also why anchoring to the start of the string removes the behaviour while anchoring to end does not.