Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: Regular expressions across multiple lines

by graff (Chancellor)
on Apr 24, 2016 at 21:29 UTC ( #1161398=note: print w/replies, xml ) Need Help??

in reply to Regular expressions across multiple lines

I think your regex could be simpler. Apart from that, given what you've said about the task and the data, I'd take a stack approach to handling the input -- something like this:
#!/usr/bin/perl use strict; use warnings; my @stack; my $buffer; my $regex = qr/^.*?(.{5}abc(?:.{10})def.{5})/; my $target_length = 26; # number of characters needed for a match while (<DATA>) { chomp; push @stack, $_; $buffer = join( "", @stack ); if ( $buffer =~ s/$regex// ) { my $target = $1; while ( $target ) { print "Found /$target/ after reading $. lines\n"; $target = ( $buffer =~ s/$regex// ) ? $1 : undef; } @stack = ( $buffer ); } else { while ( length( $buffer ) >= $target_length + length( $stack[0 +] )) { shift @stack; $buffer = join( "", @stack ); warn sprintf( "No match at line %d; stack is %d lines, %d +chars\n", $., scalar @stack, length( $buffer )); } } } __DATA__ sample data with five matches... foo bar 5CHRSabc_TEN_CHRS1def5chrs bax qax moo gar 5 Chrsab c_Ten_Chrs2 de f5Chrsnax zax 5cHrSabc_TeN_ ChRs3def5 chrs etc. and so on and so on and so on ad nausem fivecabc0123456789defmtch4 and then another FIVECabc98765432 +10defMTCH5 and then nothing useful after that forever more up to the end
That will concatenate lines onto a stack, removing line terminations as it goes. As soon as there's a match, it's reported to STDOUT, and the stack is reset to start where the match ended.

If there's no match for an extended stretch of data, the initial line is shifted off the stack so long as the overall length of the remaining lines is enough to hold a match. (I put messages to STDERR to report this, just to see it work.)

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2021-03-04 22:52 GMT
Find Nodes?
    Voting Booth?
    My favorite kind of desktop background is:

    Results (108 votes). Check out past polls.