Regex replacement operation

Peter Abel p-abel at t-online.de
Thu Jan 16 16:28:10 EST 2003


Cliff Wells <clifford.wells at attbi.com> wrote in message news:<mailman.1042698629.26788.python-list at python.org>...
> On Wed, 2003-01-15 at 20:37, David K. Trudgett wrote:
> > I'm trying to write a little micro function in Python that takes a
> > string with numeric dates in it and changes those dates into an
> > ISO8601 format. The dates in the input string are in a consistent
> > format, so that simplifies it. In Perl, I could write something like
> > the following to do it:
> > 
> > $str = 'Today is 16-1-2003 or 16-01-2003. New Year was 1-1-2003, reportedly.';
> > 
> > $str =~ s/ \b (\d{1,2}) - (\d{1,2}) - (\d{4}) \b /
> >     $3 . '-' . sprintf('%02d', $2) . '-' . sprintf('%02d', $1) /gxe;
> > 
> > which would make $str contain:
> > 
> > "Today is 2003-01-16 or 2003-01-16. New Year was 2003-01-01, reportedly."
> > 
> > 
> > How would I go about doing that in Python?
> > 
> > I've looked up the "re" module, but don't see any "substitute"
> > command, so it seems a different approach may be in order.
> 
[snip]

There is one!

>>> import re
>>> s = 'Today is 16-1-2003 or 16-01-2003. New Year was 1-1-2003,
reportedly.'
>>> # define a formatting-function
>>> format=lambda match:'%04d-%02d-%02d'%(int(match.group(3)),int(match.group(1)),int(match.group(2)))
>>> # and substitute
>>> re.sub(r'(\d+)-(\d+)-(\d+)',format,s)
'Today is 2003-16-01 or 2003-16-01. New Year was 2003-01-01,
reportedly.'
>>> 

Regards,
Peter




More information about the Python-list mailing list