pattern matching

Chris Rebert clp2 at rebertia.com
Wed Feb 23 22:24:57 EST 2011


On Wed, Feb 23, 2011 at 6:37 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Wed, 23 Feb 2011 21:11:53 -0500, monkeys paw wrote:
>> if I have a string such as '<td>01/12/2011</td>' and i want to reformat
>> it as '20110112', how do i pull out the components of the string and
>> reformat them into a YYYYDDMM format?
>
> data = '<td>01/12/2011</td>'
> # Throw away tags.
> data = data[4:-5]
> # Separate components.
> day, month, year = data.split('/')
> # Recombine.
> print(year + month + day)
>
>
> No need for the sledgehammer of regexes for cracking this peanut.

Agreed. But "Just 'Cause"(tm), and in order to get in some regex practice:

from re import compile
regex = compile("(\d\d)/(\d\d)/(\d{4})")
for match in regex.finditer(data):
    day, month, year = match.groups()
    print(year + month + day)

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list