From: Robert Klemme Date: 2011-04-06T18:42:28+09:00 Subject: Re: Match a pattern multiple times, returning matches, captures and offset? On Wed, Apr 6, 2011 at 3:37 AM, 7stud -- wrote: > Markus Fischer wrote in post #991092: >> >> But here I'm missing the further possible matches, "_bar_" and "bar". Or >> the #scan approach: >> >> ruby-1.9.2-p180 :004 > m = "_foo_ _bar_".scan(/_(\w+)_/) >>  => [["foo"], ["bar"]] >> >> But in this case I've even less information, the match including _foo_ >> or _bar_ is not present and I can't get the offsets too. >> >> I re-read the documentation for Regexp#match > > If you look at the preamble in the docs for the MatchData class, you can > retrieve a MatchData object using Regexp.last_match, which you can call > inside a scan() block: When doing nested matching it may be better to use $~ because that is local to the current stack frame which Regexp.last_match isn't. Example with relative offsets as well: irb(main):022:0> str.scan /_(\w+)_/ do irb(main):023:1* 2.times {|i| p [$~[i], $~.offset(i), $~.offset(i).map {|o| o - $~.offset(0)[0]}]} irb(main):024:1> end ["_foo_", [0, 5], [0, 5]] ["foo", [1, 4], [1, 4]] ["_bar_", [6, 11], [0, 5]] ["bar", [7, 10], [1, 4]] => "_foo_ _bar_" Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/