Addendum:

The problem has been solved, but your code is not as efficient and robust as it could be.
One way to deal with robust input validation, would be to split the input on ][, then split individual records on |, and then use regexes to validate the individual fields. Which is along the lines of what other commenters have suggested.

However, it is actually possible to do it all with a single regex, and not only get super-strict input validation with useful error handling, but also maximize performance (especially for large inputs):

my $data = '[-3|1|29x250+46+26|200+300+544|Get]' . '[-3|1|29x250+46+26|200+300+444|Get]' . '[-3|1|29x250+34#$%#$INVALID4|Get]' . '[-3|1|29x250+46+26|200+300+244|Get]' . '[#$(GARBAGE'; while ($data =~ /\G \[ (?: ([^|]*) \| ([^|]*) \| (\d+) x (\d+) \+ (\d+) \+ (\d+) \| (\d+) \+ (\d+) \+ (\d+) \| ([^|]*) | (.*?) ) \]/xgc) { if (defined $1) { say "Found record: $1, $2, $3, $4, $5, $6, $7, $8, $9, $10"; } else { say "WARNING: Skipping invalid record: $11"; } } if (pos $data != length $data) { say "WARNING: Could not extract records from remaining input: ", substr($data, pos $data); } pos($data) = undef;
Output:
Found record: -3, 1, 29, 250, 46, 26, 200, 300, 544, Get Found record: -3, 1, 29, 250, 46, 26, 200, 300, 444, Get WARNING: Skipping invalid record: -3|1|29x250+34#$%#$INVALID4|Get Found record: -3, 1, 29, 250, 46, 26, 200, 300, 244, Get WARNING: Could not extract records from remaining input: [#$(GARBAGE

If you're not clear on how it works, read the perlretut section on Global matching.


In reply to Re: Perl Regex by smls
in thread Perl Regex by Buddyhelp

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.