How to capture all conditions using regex

Hello,

irb(main):001:0> x=“123 456 789”
=> “123 456 789”

irb(main):003:0> if /\d{3}/ =~ x
irb(main):004:1> puts $&
irb(main):005:1> end
123

For the statement above, I want to capture all “123” and “456” and
“789”, not the only “123”.
How to do it (must use regex)? Thanks.

The regex itself seems okay…
irb(main):015:0> x.scan(/\d{3}/)
=> [“123”, “456”, “789”]

“789”, not the only “123”.
How to do it (must use regex)? Thanks.

Try to use the block version of gsub:

x.gsub(/\d{3}/) {|m| puts m}
123
456
789

Cheers,

On Mon, Jan 4, 2010 at 8:53 AM, Ruby N. [email protected]
wrote:

For the statement above, I want to capture all “123” and “456” and
“789”, not the only “123”.
How to do it (must use regex)? Thanks.

Use the scan method:

http://ruby-doc.org/core/classes/Kernel.html#M005985

irb(main):001:0> x=“123 456 789”
=> “123 456 789”
irb(main):002:0> x.scan /\d{3}/
=> [“123”, “456”, “789”]

Jesus.

On 01/04/2010 09:33 AM, Ruby N. wrote:

Thanks all for the quick response.
In perl there is a “/g” option which can be used for multi-matching.

perl -le ‘$x=“123 456 789”; @x=$x=~/\d{3}/g; print “@x”’

123 456 789

I try to find ruby’s instead one, but never thought there is already a
scan method available.

Note that even with #scan you have two options: you can either take the
Array returned or use the block form to do something whenever a match
occurs:

irb(main):004:0> s = “123 456 789”
=> “123 456 789”
irb(main):005:0> s.scan /\d+/
=> [“123”, “456”, “789”]
irb(main):006:0> s.scan /\d+/ do |match| p match end
“123”
“456”
“789”
=> “123 456 789”

Kind regards

robert

Thanks all for the quick response.
In perl there is a “/g” option which can be used for multi-matching.

perl -le ‘$x=“123 456 789”; @x=$x=~/\d{3}/g; print “@x”’

123 456 789

I try to find ruby’s instead one, but never thought there is already a
scan method available.
Thanks.