Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Perl Regex

by smls (Friar)
on Oct 10, 2013 at 12:39 UTC ( [id://1057734]=note: print w/replies, xml ) Need Help??


in reply to Perl Regex

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1057734]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-04-20 00:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found