Carlos Murdock
Carlos Murdock

Reputation: 103

Why this (dead simple) ruby regex behaves like this?

Why "whatever".gsub(/.*/, "bien") outputs "bienbien" instead of just "bien"?

I'm completely lost here :S Anyone could point me in the right direction?

Upvotes: 0

Views: 45

Answers (1)

Denis de Bernardy
Denis de Bernardy

Reputation: 78423

You can see what's happening using a block:

>> 'foo'.sub(/.*/) { |m| p m; 'bar' }
"foo"
=> "bar"
>> 'foo'.gsub(/.*/) { |m| p m; 'bar' }
"foo"
""
=> "barbar"
>> 'foo'.gsub(/^.*/) { |m| p m; 'bar' }
"foo"
=> "bar"
>> 'foo'.gsub(/^.*$/) { |m| p m; 'bar' }
"foo"
=> "bar"
>> 'foo'.gsub(/.*$/) { |m| p m; 'bar' }
"foo"
""
=> "barbar"
>> 'foo'.gsub(/.+/) { |m| p m; 'bar' }
"foo"
=> "bar"

Put another way, gsub will continue matching, and matches an empty string at the very end a line. (And that is arguably a bug.)

Upvotes: 1

Related Questions