in reply to Matching multiple patterns with regex
The regex approach needs to look for the "From:" and "Subject:" (and other field labels) only when they appear at the beginning of a line, and it can stop reading input as soon as all the desired fields are found.
Note the regex uses the initial anchor character (^) and non-capturing grouping parens. (You could just as well use the simpler capturing parens, without the "?:" -- this would add a slight bit of extra processing, but not enough to worry about here.)my @fields = qw/From: Subject:/; # you can add more if/when you want my $field_regex = join( "|", @fields ); my @field_lines; while (<$fh>) { push( @field_lines, $_ ) if ( /^(?:$field_regex) / ); last if @field_lines == @fields; } push @field_lines, ""; print join( "\n", sort @field_lines );
(updated to include parens around the args for the first "push" call, just because I like using parens around function args)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Matching multiple patterns with regex
by afoken (Chancellor) on Oct 31, 2015 at 07:45 UTC | |
by graff (Chancellor) on Oct 31, 2015 at 15:38 UTC |