[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Iterating through the RE Group Variables (i.e., $1 thru $9

Randy Kramer

3/27/2005 10:15:00 PM

I've written a quick and dirty regular expression tester, but there's one
thing I'd like to try to clean up.

At the moment, to display all the groups, I have a series of print statements
like:

print $1.to_s + "\n"
print $2.to_s + "\n"
...
print $9.to_s + "\n"

Surely there's a more Ruby'esque way, but I haven't found it so far. I'd like
to create a loop, or a range, or something and then iterate over it. Here
are snippets of some of the things I've tried, but I don't seem to be making
any progress (and I'm shooting in the dark):

eval($#{i})

eval $#{i}

[1..9].each {|i| print $i.to_s + "\n"}

[1..9].each {|i| print $#{i}.to_s + "\n"}

Is there a way to increment from $1 through $9 in some kind of loop?

Thanks!
Randy Kramer

(I know I'll feel dumb when somebody points out how simple it is, but ...)


2 Answers

Florian Gross

3/27/2005 10:25:00 PM

0

Randy Kramer wrote:

> I've written a quick and dirty regular expression tester, but there's one
> thing I'd like to try to clean up.
>
> At the moment, to display all the groups, I have a series of print statements
> like:

puts $~.captures

Avoiding the perlish variable:

if md = /foo(.+)bar(.+)qux/.match(str) then
puts md.captures
end

or

puts Regexp.last_match.captures

Randy Kramer

3/28/2005 3:44:00 PM

0

On Sunday 27 March 2005 05:29 pm, Florian Gross wrote:
> puts $~.captures
>
> Avoiding the perlish variable:
>
> if md = /foo(.+)bar(.+)qux/.match(str) then
> puts md.captures
> end
>
> or
>
> puts Regexp.last_match.captures

Thanks! Those definitley seem more Rubyish, and once I realized the results
were in an array, I was able to do this (to format the output):

(1..10).each {|i| puts "$" + i.to_s + " is: " + Regexp.last_match.captures[i -
1].to_s}

Gives, e.g:

$1 is: http:
$2 is: //blah/blah
...

And I can see how to make unit tests for each RE, although I may wait until
all my REs are done and I have a scanner, then do a "unit test" on a specific
document with examples of each thing that should be matched and its proper
translation (or parsing).

regards,
Randy Kramer