Parsing text

Noah noah at noah.org
Mon Dec 19 20:54:45 EST 2005


sicvic wrote:
> I was wondering if theres a way where python can read through the lines
> of a text file searching for a key phrase then writing that line and
> all lines following it up to a certain point, such as until it sees a
> string of "---------------------"
>...
> Thanks,
> Victor

You did not specify the "key phrase" that you are looking for, so for
the sake
of this example I will assume that it is "key phrase".
I assume that you don't want "key phrase" or "---------------------" to
be returned
as part of your match, so we use minimal group matching (.*?)
You also want your regular expression to use the re.DOTALL flag because
this
is how you match across multiple lines. The simplest way to set this
flag is
to simply put it at the front of your regular expression using the (?s)
notation.

This gives you something like this:
    print re.findall ("(?s)key phrase(.*?)---------------------",
your_string_to_search) [0]

So what that basically says is:
    1. Match multiline -- that is, match across lines (?s)
    2. match "key phrase"
    3. Capture the group matching everything (?.*)
    4. Match "---------------------"
    5. Print the first match in the list [0]

Yours,
Noah




More information about the Python-list mailing list