From: ts Date: 2004-04-04T00:53:47+09:00 Subject: Re: [newbie] How do I match a regex multiple times? >>>>> "R" == Robo writes: R> e.g. puts 'robo ruler ruby'.match(/r\w+/) String#scan svg% ri String#scan ------------------------------------------------------------ String#scan str.scan(pattern) => array str.scan(pattern) {|match, ...| block } => str ------------------------------------------------------------------------ Both forms iterate through _str_, matching the pattern (which may be a +Regexp+ or a +String+). For each match, a result is generated and either added to the result array or passed to the block. If the pattern contains no groups, each individual result consists of the matched string, +$&+. If the pattern contains groups, each individual result is itself an array containing one entry per group. a = "cruel world" a.scan(/\w+/) #=> ["cruel", "world"] a.scan(/.../) #=> ["cru", "el ", "wor"] a.scan(/(...)/) #=> [["cru"], ["el "], ["wor"]] a.scan(/(..)(..)/) #=> [["cr", "ue"], ["l ", "wo"]] And the block form: a.scan(/\w+/) {|w| print "<<#{w}>> " } print "\n" a.scan(/(.)(.)/) {|a,b| print b, a } print "\n" _produces:_ <> <> rceu lowlr svg% Guy Decoux