Forum: Ruby getting the results of a simple regex

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D48be99143e13e40d1c44a4da63a53f4?d=identicon&s=25 Mongeta 99 (raimon)
on 2009-04-06 19:13
Hello,


I'm playing for my very first time with Regex ...

I want to split some numbers, and get their results:

Given this string:

18,04 2,89 20,93 2,71 18,22

I want to get every number before a comma, and two digits later, and all
the groups.

I think it should work this way but I can only get the first result ...


/(\d+,\d{2})/ =~ "18,04 2,89 20,93 2,71 18,22"
=> 0
>> $1
=> "18,04"
>> $2
=> nil
>> $3
=> nil
>> $4
=> nil
>> $5
=> nil


Playing with the http://www.rubular.com/ I can get the result that I
want ...

I also tried the Regexp.last_match but I'm getting the same, only the
first value ...

what I'm doing wrong ?

thanks!

r.
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-04-06 20:30
(Received via mailing list)
On 06.04.2009 19:12, Raimon Fs wrote:
>
>>> $2
> want ...
>
> I also tried the Regexp.last_match but I'm getting the same, only the
> first value ...
>
> what I'm doing wrong ?

You do not use String#scan. :-)

Btw, you do not need the grouping as you want the complete match anyway.

Kind regards

  robert
D48be99143e13e40d1c44a4da63a53f4?d=identicon&s=25 Mongeta 99 (raimon)
on 2009-04-06 20:39
Robert Klemme wrote:
> On 06.04.2009 19:12, Raimon Fs wrote:
>>
>>>> $2
>> want ...
>>
>> I also tried the Regexp.last_match but I'm getting the same, only the
>> first value ...
>>
>> what I'm doing wrong ?
>
> You do not use String#scan. :-)


=> var="18,04 2,89 20,93 2,71 18,22"
>> a=var.scan(/\d+,\d{2}/)
=> ["18,04", "2,89", "20,93", "2,71", "18,22"]
>> a[0]
=> "18,04"
>> a[1]
=> "2,89"
>> a[2]
=> "20,93"
>> a[3]
=> "2,71"
>> a[4]
=> "18,22"

:-)

thanks ....



>
> Btw, you do not need the grouping as you want the complete match anyway.

I was grouping with () because I was using:

      line =~
%r{(\d+,\d{2})(\s)(\d+,\d{2})(\s)(\d+,\d{2})(\s)(\d+,\d{2})(\s)(\d+,\d{2})}

and then $1, $2, $3, $4, ...

thanks for your help!

regards,

r.
This topic is locked and can not be replied to.