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 -- Posted via http://www.ruby-forum.com/.
Francois Beausoleil
2006-May-05 14:52 UTC
[Rails] can you do global match regular expressions?
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 ! -- Fran?ois Beausoleil http://blog.teksol.info/
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.> 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??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.