re sub help

Mike Meyer mwm at mired.org
Sat Nov 5 03:35:53 EST 2005


s99999999s2003 at yahoo.com writes:
> 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\]")
>
> 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"..?
> thanks.

Newlines are magic to regular expressions. You use the flags in re to
change that. In this case, you want . to match them, so you use the
DOTALL flag:

>>> a = "this\nis\na\nsentence[startdelim]this\nis\nanother[enddelim]this\nis\n"
>>> t = re.compile(r"\[startdelim\](.*)\[enddelim\]", re.DOTALL)
>>> t.findall(a)
['this\nis\nanother']
>>> 

    <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list