On 12.11.2008 17:14, Jes=FAs Gabriel y Gal=E1n wrote:
> On Wed, Nov 12, 2008 at 4:52 PM, Dave Roberts <dave.a.roberts / gmail.com=
> wrote:
>> Hello!  I have a string: "Hello - 1 - World"
>>
>> irb(main):017:0> a =3D "Hello - 1 - World"
>> =3D> "Hello - 1 - World"
>>
>> I want to chop off the "Hello - " part.  Hello could be any word, so I=

>> want to match it generically.
>> To match the first minus I do this:
>>
>> irb(main):018:0> b =3D a.sub(/\s-\s/, "")
>> =3D> "Hello1 - World"
>>
>> Good!  Now to get rid of the first word I try this:
>>
>> irb(main):019:0> c =3D a.sub(/.*\s-\s/, "")
>> =3D> "World"
>>
>> Bad!  It matched to the second minus!  Why does sub do this?  I though=
t
>> it was supposed to match the first occurrence only.
>=20
> Because * by default is greedy, so it tries to match as much as it can.=

> Try this:
>=20
> irb(main):002:0> c =3D a.sub(/.*?\s-\s/, "")
> =3D> "1 - World"

Other variants would be

irb(main):001:0> a =3D "Hello - 1 - World"
=3D> "Hello - 1 - World"
irb(main):002:0> a[/\d+\s+-.*/]
=3D> "1 - World"
irb(main):003:0> a.sub /^\S+\s+-\s+/, ''
=3D> "1 - World"
irb(main):004:0> a.sub /^\w+\s+-\s+/, ''
=3D> "1 - World"
irb(main):005:0>

Cheers

	robert