regular expression help (was GUI re builder)

Bengt Richter bokr at oz.net
Tue Apr 1 01:21:16 EST 2003


On Mon, 31 Mar 2003 11:47:41 -0600, Stephen Boulet <stephen.boulet at motorola.com> wrote:

>Matt Gerrans wrote:
>> There should be an redemo.py in the tools/scripts directory, under Python22.
>
>Thanks Matt.
>
>I have my date-matching re (for incidences of 3/31/03 or 12/3/2003, for example):
>
>s = '3/31/03 some text 12/3/2003 some more text.'
>p = re.compile('\d+/\d+/\d+')
>s = p.sub('\n\n', s)
>
>Now, I want to precede each match with two newlines. How do I do this, instead 
>of replacing each match like above?
>
Do you mean that your
    s = '3/31/03 some text 12/3/2003 some more text.'
should become just have \n\n inserted, to become equal to
    s2 = """

3/31/03 some text 

12/3/2003 some more text."""
?

If so, perhaps this would serve:

 >>> import re
 >>> rx = re.compile(r'(\d+/\d+/\d+)')
 >>> s = '3/31/03 some text 12/3/2003 some more text.'
 >>> rx.sub('\n\n\\1',s)
 '\n\n3/31/03 some text \n\n12/3/2003 some more text.'
 >>> print rx.sub('\n\n\\1',s)


 3/31/03 some text

 12/3/2003 some more text.

Regards,
Bengt Richter




More information about the Python-list mailing list