How to find all matches using ruby regex?

I have the following ruby code and I want to find all matched
“data-1.2.5.tar.gz” and “data-1.2.7.tar.gz”, then stored in $1 and $2.
When I executed it and I found $1 is “data-1.2.5.tar.gz”, but $2 is nil.
How can I get $2 is “data-1.2.7.tar.gz”?

=============================================================
string1 = “data-1.2.5.tar.gz and data-1.2.7.tar.gz and readme.”

if string1 =~ /(data-\d+.\d+.\d+.tar.gz)/
print "Matched on ", $1, “\n”
print "Matched on ", $2, “\n”

else
puts “NO MATCH”
end

“data-1.2.5.tar.gz and data-1.2.7.tar.gz and readme.”.scan
/data-\d+.\d+.\d+.tar.gz/

=> [“data-1.2.5.tar.gz”, “data-1.2.7.tar.gz”]

Hope this helps

2011/8/24 michael xu [email protected]

On Thu, Aug 25, 2011 at 12:14 AM, michael xu [email protected]
wrote:

print "Matched on ", $2, “\n”

else
puts “NO MATCH”
end

Are you sure there are always exactly two of them? If not, #scan is
better:

irb(main):001:0> string1 = “data-1.2.5.tar.gz and data-1.2.7.tar.gz and
readme.”
=> “data-1.2.5.tar.gz and data-1.2.7.tar.gz and readme.”
irb(main):002:0> string1.scan /data-\d+(?:.\d+)*.tar.gz/
=> [“data-1.2.5.tar.gz”, “data-1.2.7.tar.gz”]

Kind regards

robert

Yes, it works fine.
Thank you Nik!

Nik Z. wrote in post #1018346:

You never set the 2nd set of parens (…) in the original regex:
(data-\d+.\d+.\d+.tar.gz)/

therefore, no $2 for you…

change to regex to /(data\S+) and (data\S+)/, and you get $1 and $2…

You never set the 2nd set of parens (…) in the original regex:
(data-\d+.\d+.\d+.tar.gz)/

therefore, no $2 for you…

change to regex to /(data\S+) and (data\S+)/, and you get $1 and $2…

michael xu wrote in post #1018329:

I have the following ruby code and I want to find all matched
“data-1.2.5.tar.gz” and “data-1.2.7.tar.gz”, then stored in $1 and $2.
When I executed it and I found $1 is “data-1.2.5.tar.gz”, but $2 is nil.
How can I get $2 is “data-1.2.7.tar.gz”?

=============================================================
string1 = “data-1.2.5.tar.gz and data-1.2.7.tar.gz and readme.”

if string1 =~ /(data-\d+.\d+.\d+.tar.gz)/
print "Matched on ", $1, “\n”
print "Matched on ", $2, “\n”

else
puts “NO MATCH”
end