Hi,
In message "[ruby-talk:8477] Re: A newbie question (about regexp)"
on 01/01/02, "Robert Gustavsson" <robertg / swipnet.se> writes:
>> STDOUT.sync = true
>
>I got the code from the Ruby User's Guide. Maybe this .sync is smarter than
>the .flush calls?
It's depend on the case. In this case, flush is called twice but it
blur meaning of the code (at least for me). However, I would not like
to patch User's Guide because use of sync= needs extra explanation.
>That is, to be able to access each of the matches of the regexp pattern. But
>this gsub! method, it does replacements in the original string. What is the
>easiest and smartest way to do the following:
>
>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).
If you would not emaphasize by escape sequence, try this:
p "a111b222c333d".scan(/\d+/)
or
"a111b222c333d".scan(/\d+/){|i| p i}
but it doesn't replace.
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 :-(
>Maybe gsub! is the only way to do a pattern match and then be able to access
>all info about the match(es)?
No, it isn't. gsub! is the only way to match-and-replace.
-- Gotoken