Patrick He
9/26/2008 3:51:00 PM
[Note: parts of this message were removed to make it a legal post.]
IMO, lookahead is the best solution for the problem.
Mark Thomas wrote:
> On Sep 26, 10:02 am, Chris Ro <kyl...@gmx.net> wrote:
>
>> Hi,
>>
>> I have a little problem with a regex in Ruby:
>>
>> I have twos strings:
>>
>> string1 = "He is the 20th."
>> string2 = "25th"
>>
>> I wrote this to "extract" the place (20 or 25 respectively):
>>
>> place1 = string1.gsub(/.*(\d+)th.*/,'\1')
>> place2 = string2.gsub(/.*(\d+)th.*/,'\1')
>> pp place1
>> pp place1
>>
>> => "0"
>> => "5"
>>
>> Of course, I would like to get all the digits before "th". Why is only
>> the last one captured?
>>
>
> Because the .* is greedy and will get all it can, which is all but the
> last digit.
>
>
>> If anyone could please explain this, and help me come up with a regex
>> that captures 20 and 25, respectively, this would be greatly
>>
>
> place = string[/\d+(?=th)/]
>
> -- Mark.
>
>
>