Forum: Ruby on Rails can you do global match regular expressions?

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.
Cd8c9864d88bcafc164d8fdb820cc451?d=identicon&s=25 Chris Richards (chris)
on 2006-05-05 16:43
I cant figure out how to do global regular expressions in ruby.  Im not
even sure if its possible.  In the "Programming Ruby" book there is no
mention of it.

Can you do this?

text = "aaa1 bbb2   ccccc3  dddddd4 eee5"

re = /\w+\d{1}/

matches = re.match text

m[0] = "aaa1"
m[1] = nil
m[2] = nil
and so on....

Is there any way to get an array of all the matches??

Thanks
Chris
3dd4b52a0946bd698b1d1635a46ea3a3?d=identicon&s=25 François Beausoleil (fbeausoleil)
on 2006-05-05 16:54
(Received via mailing list)
Hello Chris,

2006/5/5, Chris Richards <evilgeenius@gmail.com>:
> Is there any way to get an array of all the matches??

Take a look String#scan.  Returns an array or calls into a block with
each match.

Bye !
F3f738ecc0ae99d54c4e2842cf3d520a?d=identicon&s=25 Louis Erickson (Guest)
on 2006-05-05 17:03
(Received via mailing list)
On Fri, 5 May 2006, Chris Richards wrote:

> I cant figure out how to do global regular expressions in ruby.  Im not
> even sure if its possible.  In the "Programming Ruby" book there is no
> mention of it.

They're listed as "regular expressions" in the index.  See p69 in
Programming Ruby, 2nd edition.

There is also a Regexp class, described on page 600 in the "Built-in
classes and modules" chapter.  More interestingly, see MatchData on
p537.

> m[2] = nil
> and so on....
>
> Is there any way to get an array of all the matches??

str = 'This is a fun string!'
re = /(his).*(un).*(in).*/
matches = re.match(str)

matches[1 .. matches.length].each { |m| puts m }

Note that matches[0] contains the full string that matched, so is not
part
of what you want, but 1 .. length will be.

--
Louis Erickson - lerickson@rdwarf.net - http://www.rdwarf.com/~wwonko/

Real computer scientists don't comment their code.  The identifiers are
so long they can't afford the disk space.
This topic is locked and can not be replied to.