Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: How do I extract all text between two keywords like start and end?

by chromatic (Archbishop)
on Apr 14, 2000 at 19:41 UTC ( [id://7636]=note: print w/replies, xml ) Need Help??


in reply to How do I extract all text between two keywords like start and end?

The basic regexp is:
if ($text =~ /\bstart\b(.*?)\bend\b/) { $result = $1; # do something with results }
Note that the . character matches any character but a newline (see m// if you want to span lines), the * means match zero or more times, and the ? forces * to match as few times as possible -- so it will pick up the first end instead of the last one. The \b is in there to prevent mismatches on words like 'starting' and 'backend'.

It has the limitation of not catching nested starts and ends, in which case you might go the recursion route, and write this as a function:

sub between { my $text = shift; if ($text =~ /start(.*?)end/) { $result = $1; between($result); } else { return $text; } }
That can become prohibitively expensive, depending on your data set. I suspect there's a more hideous solution involving split and join, but that's likely to be counterproductive at this point. It also depends on having balanced tags -- if you don't, don't do this!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2024-04-25 08:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found