Hello --

On Tue, 2 Jan 2001, GOTO Kentaro wrote:

> In message "[ruby-talk:8477] Re: A newbie question (about regexp)"
>     on 01/01/02, "Robert Gustavsson" <robertg / swipnet.se> writes:
> 
> >We have a string (for example "a111b222c333d")
> >We have a pattern (for example /\d+/)
> >
> >We want an array of the matches found. Either as an array of strings or as
> >an array with some other objects (MatchingData?) that give more detailed
> >information about the matches (like start and begin in the original string).

>
  [demo of String#scan]
>
> Now, String#scan and String#gsub can be considerd as iterators such
> that repeat matching with the given pattern up to end of the string,
> i.e., reciever of the method.
> 
> On the other hand, MatchingData doesn't hold older matching
> information.  MatchingData is introduced as alternative way to access
> $`, $', $1, $2 etc..., which came from Perl and some peoples think
> them make code criptic.  Thus, we can get MatchingData by $~ or
> Regexp.last_match. The latter is more descriptive and clear but typing
> `Regexp.last_match' is boresome :-(

But you can save MatchData objects -- in fact, one way to get both the
replacement and the metadata Robert wants is to adapt your earlier
code, using the block form of gsub!, to save $~ instead of just the
matched substring:

   st = "\e[7m"
   en = "\e[m"
   str = 'a1a1a1b222c3c3c3d'
   re = '\d+'
   matches = []

   str.gsub!(re) do |m|
     matches.push $~
     "#{st}#{$&}#{en}"
   end

   puts str
   puts "Matches: #{matches.size}"
   puts "2nd match began at position #{matches[1].begin(0)}"
   puts "and ended at position #{matches[1].end(0)}"

(I love the block form of gsub[!]!)


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav