On 19/10/05, Brian Schr?der <ruby.brian / gmail.com> wrote:
> On 19/10/05, Eyal Oren <eyal.oren / gmail.com> wrote:
> > Hi,
> >
> > I am parsing query expressions, using a regular expression with
> > multiple matches in it, e.g. /(\w+):(\w+)/.
> >
> > I would like some code to execute on the first match (e.g.
> > constructing some object out of it) and some other code on the second
> > match (e.g. constructing some other object).
> >
> > I can of course check the array of matches and find the non-nil
> > element, and decide which code to execute. But that becomes very
> > cumbersome with a large regex (with say 10 different matches).
> >
> > So I would rather like to attach some code in a match directly, as one
> > does in parsing generators, e.g.
> > /(\w+:do_method):(\w+:do_other_method)/.
> >
> > Would something like that be possible in Ruby? I tried searching but
> > I'm not sure how such a feature would be called.
>
> Maybe you can refactor your regexp to be used with scan.
>
> irb(main):001:0> "some words to change".scan(/\w+/) do | w | puts w.upcase end
> SOME
> WORDS
> TO
> CHANGE
> => "some words to change"
I am not sure that would help, I need to know which of the matches
occurred, because the actions are different for different matches (you
just 'put' all matches).

In your example, "Some words To change" say I want to print the
capitalised words normally, and print the others reversed. I can make
a regex that captures both these words in two groups, but scan
wouldn't work because I wouldn't know if a match was from group one or
group two.

But AFAIK I cannot ask the resulting match which regex he was matched
by, so I still do not know what to do. I could of course test each
regex on the matched word again, but that is not efficient.