From: Dave Thomas Date: 2000-08-27T06:32:00+09:00 Subject: [ruby-talk:4593] Re: Getting list of regexp matches Stephen White writes: > I don't quite understand the concept of iterators. Let's say I have an array > of regexp's containing keywords, like: > > keywords = [ /int/, /float/, /double/ ] > > then I have a file in variable, like: > > a = File.new("freddie.c").read(nil) > > I can understand how to use iterators to go through the keywords array, but > not how to get an array of matches. > > What I'd like out of this is a list of matches, like: > > [ "int", [ 56, 78, 128 ], > "float", [ 90, 400 ], > "double", [ 200, 250 } } > > Is Ruby capable of iterating through regexp matches, or do I have to restart > regexp for every match, which is wasteful of resources? Yup -- not really a problem, particularly if you don't mind having the result come back in a hash, rather than an array. Having said that, this isn't really an iterator issue: we're using gsub to to the matching and the block attached to it to accumulate the results. I'm not sure what the numbers in your result are: let's assume line numbers: keywords = /\b(int|float|double)\b/ result = Hash.new IO.foreach("freddie.c") do |line| line.gsub(keywords) { |kw| result[kw] ||= []; result[kw].push $. } end result.each { |kw, lines| print "#{kw}: #{ lines.join(', ')}\n" } Feed it freddie.c: int i; double d; float f(int j, double k) { int l; notint k; } And you get: int: 1, 3, 4 float: 3 double: 2, 3 Regards Dave