On 7/31/07, Alessandro Re <akirosspower / gmail.com> wrote:
> Hi there!
> I'm Alessandro from Italy and I started using ruby some days ago,
> so... Hello, Community! :)
>
> Well, I was trying to match a pattern multiple times. I tried both
> with normal match() and scan(), but i can't get the desired result.
>
> The subject string is something like:
> "1a2bend" or "beg1a2b3c4dend"
> more generally, it should match /^beg(\d\w)*end$/ : always a begin and
> ending pattern, and a unspecified number of central pattern.
> The problem is that the central pattern must be extracted for every
> time it's encountered.
> For example, trying with
> "x1A2B3C4Dz".scan /^(x)(\d\w)*(z)$/
> returns
> [["x", "4D", "z"]]
> while i need something like
> [["x", "1A", "2B", "3C", "4D", "z"]]
>
> Why does ()* match just the last one? How can i get all the ()* that it matches?
>
> Probabily i'm doing something wrong, but can't understand where :\

Try:

if "x1A2B3C4Dz" =~ /^(x)((?:\d\w)*)(z)$/
    a, b = $1, $3 #
    return [a] + $2.scan(/\d\w/).flatten + [b]
end

I don't know if it's possible to do it in one run though, maybe you
could use split as well...
Take care when doing nested searches as they will overwrite $1..9
(that's why I used a and b)

J.