[Tutor] extracting lines between patterns.

Alan Gauld alan.gauld at btinternet.com
Mon May 14 21:01:32 CEST 2012

On 14/05/12 08:31, Bala subramanian wrote:
> Friends,
> Could someone please give some hint on how to extract lines between two
> patterns in a file. I use the re module to compile my patterns but not
> able to figure out how i can use these patterns to extract the lines
> lying in between.

Without much detail here goes the generic pattern in pseudo code:

active_flag = False
for line in file:
    if not active_flag:
       if start_pattern in line:
           active_flag = True
       if end_pattern in line:
           active_flag = False   # or break if only one group possible
       else: #process line

You can tweak the logic to make it more efficient but at the cost of 

Hopefully that gives you a starting point.

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list