how to capture all conditions using regex

R

Ruby Newbee

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.
 
J

joe chesak

[Note: parts of this message were removed to make it a legal post.]

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

Fleck Jean-Julien

irb(main):001:0> x=3D"123 456 789"
=3D> "123 456 789"

irb(main):003:0> if /\d{3}/ =3D~ x
irb(main):004:1> =A0 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.

Try to use the block version of gsub:
123
456
789

Cheers,

--=20
JJ Fleck
PCSI1 Lyc=E9e Kl=E9ber
 
J

Jesús Gabriel y Galán

Hello,

irb(main):001:0> x=3D"123 456 789"
=3D> "123 456 789"

irb(main):003:0> if /\d{3}/ =3D~ x
irb(main):004:1> =A0 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.

Use the scan method:

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

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

Jesus.
 
R

Ruby Newbee

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.
 
R

Robert Klemme

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top