Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: how to extract string by possible groupings?

by AnomalousMonk (Archbishop)
on Jun 02, 2014 at 16:31 UTC ( [id://1088282]=note: print w/replies, xml ) Need Help??


in reply to how to extract string by possible groupings?

The approach of factoring regex sub-expressions can also be helpful.  $RE{num}{real} is from Regexp::Common. The  $title regex won't properly match something like  '/foo/bar/test.c' so this regex (and the others) may need to be refined; this is easier to do if regexes have been factored into individual components.

c:\@Work\Perl\monks>perl -wMstrict -le "use Regexp::Common; ;; my @lines = ( 'test1.cpp 0.00% of 21 0.00% of 16', 'test2.c None 16.53% of 484', 'test3.h 0.00% of 138 None', '/x/y/foo.c 0.00% of 1 None', ); ;; my $title = qr{ \w+ (?: [.] \w+)* }xms; my $percent = qr{ $RE{num}{real} % \s+ of \s+ \d+ }xms; my $none = qr{ None }xms; ;; for my $line (@lines) { print qq{line '$line'}; die qq{bad line: '$line'} unless my ($t, $p1, $p2) = $line =~ m{ \A ($title) \s+ ($percent | $none) \s+ ($percent | $none) \s* \ +z }xms; print qq{ title: '$t' pcent1: '$p1' pcent2: '$p2'}; } " line 'test1.cpp 0.00% of 21 0.00% of 16' title: 'test1.cpp' pcent1: '0.00% of 21' pcent2: '0.00% of 16' line 'test2.c None 16.53% of 484' title: 'test2.c' pcent1: 'None' pcent2: '16.53% of 484' line 'test3.h 0.00% of 138 None' title: 'test3.h' pcent1: '0.00% of 138' pcent2: 'None' line '/x/y/foo.c 0.00% of 1 None' bad line: '/x/y/foo.c 0.00% of 1 None' at -e line 1.

Update: Changed code example to better demonstrate error handling.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2024-04-23 12:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found