Regex replacement operation

David K. Trudgett dkt at registriesltd.com.au
Thu Jan 16 18:17:06 EST 2003


On Thursday 2003-01-16 at 13:28:10 -0800, Peter Abel wrote:

> > > $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!

Doh! I swear I'm going blind.


> 
> >>> 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.'
> >>> 

Nice approach.

Thanks for the help! Now I have to decide which approach to use.
Decisions, decisions!

David Trudgett







More information about the Python-list mailing list