[Tutor] how to print the match middle part out

Steven D'Aprano steve at pearwood.info
Thu Dec 15 19:04:01 CET 2011


lina wrote:
> Hi,
> 
> For following:
> 
> aaa
> model 0
> bbb
> acb
> model 1
> ccc
> 
> 
> How can I set regexp1 as "model 0" and end "model 1"

In English, we have a saying "When all you have is a hammer, everything looks 
like a nail". Don't make the mistake of thinking that regexes are your hammer.

In my opinion, this example is best solved with a filter function, not a 
regex. Here is a simple example:


def filter_lines(lines, start, end):
     lines = iter(lines)
     # Skip lines before matching start.
     for line in lines:
         if line == start:
             yield line
             break
     # Show lines after matching start, but before matching end.
     for line in lines:
         if line == end:
             break
         yield line


text = """aaa
model 0
bbb
acb
model 1
ccc
"""


And the output:

py> for line in filter_lines(text.split('\n'), 'model 0', 'model 1'):
...     print line
...
model 0
bbb
acb



-- 
Steven



More information about the Tutor mailing list