re sub help

Fredrik Lundh fredrik at pythonware.com
Sat Nov 5 03:34:07 EST 2005


<s99999999s2003 at yahoo.com> wrote:

> i am still interested about using re, i find it useful. am still
> learning it's uses.
> so i did something like this for a start, trying to get everything in
> between [startdelim] and [enddelim]
>
> a =
> "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n"
>
> t = re.compile(r"\[startdelim\](.*)\[enddelim\]")

"*" is greedy (=searches backwards from the right end), so that won't
do the right thing if you have multiple delimiters

to fix this, use "*?" instead.

> t.findall(a)
> but it gives me []. it's the "\n" that prevents the results.
> why can't (.*) work in this case? Or am i missing some steps to "read"
> in the "\n"..?

    http://docs.python.org/lib/re-syntax.html

     (Dot.) In the default mode, this matches any character except
    a newline. If the DOTALL flag has been specified, this matches any
    character including a newline.

to fix this, pass in re.DOTALL or re.S as the flag argument, or
prepend (?s) to the expression.

</F>






More information about the Python-list mailing list