[Tutor] extend my re

Mark Tolonen metolone+gmane at gmail.com
Sat Nov 22 20:07:32 CET 2008


"Ricardo Aráoz" <ricaraoz at gmail.com> wrote in message 
news:49281CBB.1090607 at gmail.com...
> Hi, I've got a half working re but I can't find a way to give it the
> final touch.
> Let's say I have (it would actually be source code file) :
>>>> import re
>>>> MyString = """Algo
> ... Start
> ...     otro
> ...     comment
> ...     otro
> ...     comment
> ...     comment
> ...     otro
> ... end
> ...     """
>>>> MyPattern =
> re.compile(r'(.*?Start.*?)((comment.*?)*)(comment)(.*?end)', re.S)
>
>>>> print MyString
> Algo
> Start
>    otro
>    comment
>    otro
>    comment
>    comment
>    otro
> end
>
>>>> print MyPattern.sub(r'\1\2/*\4*/\5', MyString)
> Algo
> Start
>    otro
>    comment
>    otro
>    comment
>    /*comment*/
>    otro
> end
>
> Which is basically ok. I have to find the last "comment" in the block
> and comment it. But I'd like to comment the whole line, my desired
> output would be :
> Algo
> Start
>    otro
>    comment
>    otro
>    comment
> /*    comment*/
>    otro
> end
>
> And if there was something after the "comment" I would also like it to
> be commented :
> from:
>    comment and something else
> to :
> /*   comment and something else*/
>
> any help?

A quick attempt that works for your example:

    MyPattern = 
re.compile(r'(.*?Start.*?)((\n\s*comment.*?)*\n)(\s*comment.*?)(\n.*?end)', 
re.S)

You might look into something like pyparsing instead of a complicated re.

-Mark





More information about the Tutor mailing list