Dear fellow monks, I have a regex with capturing brackets and I would like to find the position and the contents of the brackets for every match in a string. E. g. given the following regex and string:

my $regex = qr/(\d\d):(\d\d)(?::(\d\d))?/; # 01234567890123456 my $string = "11:30 or 11:29:53";
I would like to get the result:

$res = { 0 => ['11', '30', undef], 19 => ['11', '29', '53'] }

If I evaluate the the the regex in scalar context, I can get the position of each match, like this:

$res->{pos ($string)} = [$1, $2, $3] while $string = /$regex/g;
But the problem is that I read the regex from a file, so I have no idea how many capturing brackets it contains (and I think it is rather hard to find that out, isn't it?). Therefore I don't how many $n to put in the result array.

On the other hand, I can evaulate the regex in list context, as in:

@res = $string = /$regex/g;
but then I get neither the positions nor the information how often the string matched (I don't know how many capturing brackets the regex contains!). Is there any way to get the contents of the brackents in an array, but only for one match, and to iterate over all matches in a while loop, as m//g does in scalar context?

Thanks for any advice,

pike


In reply to Multiple matches of a regex by pike

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.