I have run into a little problem in extracting information from a bunch of files. As I loop through all the files, I slurp each one in and then look for information matching certain criteria. For simplicity's sake, lets say that the file contents is

$fc = 'abcdfoofrobnicatebardefforspambazghi';

I then search for certain patterns in the file and capture them using a regex, say:

$re1 = qr/fo.*?ba./;

I capture them into an array for later analysis thus:

@excerpts = $fc =~ /$re1/g;

The above yields two entries in @excerpts:

foofrobnicatebar forspambaz

Later, when I get to analyzing the excerpts, I want to search each one for patterns within each match using almost the same regex with capture groups:

$re2 = qr/(fo.)(.*?)(ba.)/;

This gives me

foo frobnicate bar for spam baz

My question is this: The expressions I am really using are much more complicated in the two regexes, $re1 and $re2, and there are orders of magnitude more captures than the two shown here. If I make a change to one regex, I have to change the other. This can be a hassle in big ugly expressions, and I have already failed once to notice they were not in sync. It would be nice to have only one regex, but if I were to use the second expression in the first capture, I would get

@excerpts = $fc =~ /$re2/g; foo frobnicate bar for spam baz

Six entries in @excerpts

Having capture groups in a /g capture makes each capture group add an element to the array instead of the whole regex adding one. Is there an easier way than having two almost identical regexes? Can I have one regex with capture groups, but keep it from making each capture group create an array element under /g?


In reply to Behavior of /g when there are capture groups by ExReg

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.