Forum: Ruby Stumped: How do I iterate over regular expression matches?

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.
Xeno C. (Guest)
on 2006-04-26 22:24
(Received via mailing list)
I looked for an iterator, and there may be something, but I don't
recognize it.
I also tried:
while (x =~ /something/ )
p $1

end
and it just printed out the same match over and over.  Perl does this
very
nicely, but google and pickaxe are not helping me do it in Ruby.  Sorry
if this
is obvious.

xc
James G. (Guest)
on 2006-04-26 22:30
(Received via mailing list)
On Apr 26, 2006, at 1:21 PM, Xeno C. wrote:

> Sorry if this
> is obvious.

You are looking for String#scan.  Hope that helps.

James Edward G. II
Ryan L. (Guest)
on 2006-04-26 22:33
(Received via mailing list)
On 4/26/06, Xeno C. <removed_email_address@domain.invalid> wrote:
> I looked for an iterator, and there may be something, but I don't recognize it.

Have you looked at String#scan?

irb(main):001:0> s='abc blah blah abc something else abc'
=> "abc blah blah abc something else abc"
irb(main):002:0> s.scan(/abc/)
=> ["abc", "abc", "abc"]

Ryan
John J. (Guest)
on 2006-04-26 23:48
(Received via mailing list)
You can use String#scan:

irb
irb(main):001:0> a="This is a test of this thing for this guy on the
net."
=> "This is a test of this thing for this guy on the net."
irb(main):002:0> a.scan(/is/)
=> ["is", "is", "is", "is"]
irb(main):003:0> a.scan(/[^ ]is/)
=> ["his", "his", "his"]
irb(main):004:0> a.scan(/[^ ]+is/)
=> ["This", "this", "this"]
irb(main):005:0>

or:

a.scan(/[^ ]+is/) { |match|
  puts "#{match} is a match of the regexp."
}
This is a match of the regexp.
this is a match of the regexp.
this is a match of the regexp.

Regards,
  JJ



On Wednesday, April 26, 2006, at 02:21PM, Xeno C.
<removed_email_address@domain.invalid> wrote:

>xc
>
>
>


---
Help everyone. If you can't do that, then at least be nice.
Xeno C. (Guest)
on 2006-04-27 10:00
(Received via mailing list)
Thank you all for the answers.  I should have guessed to look at the
String methods.

Sincerely, Xeno
xc
Logan C. (Guest)
on 2006-04-27 10:12
(Received via mailing list)
On Apr 27, 2006, at 1:58 AM, Xeno C. wrote:

> Thank you all for the answers.  I should have guessed to look at
> the String methods.
>
> Sincerely, Xeno
> xc

Just a random thought, but doesn't it seem like this question belongs
in some sort of FAQ? (Probably this one: http://www.rubycentral.com/
faq/rubyfaqall.html) It seems a pretty common question, especially
for people coming from perl.
This topic is locked and can not be replied to.