[Python-ideas] idea: Template.match function

Jared Grubb jared.grubb at gmail.com
Sat Oct 11 03:38:41 CEST 2008


On 10 Oct 2008, at 17:50, Joe Strout wrote:

>    >>> from string import Template
>    >>> s = Template('$name was born in ${country}')
>    >>> print s.match('Guido was born in the Netherlands')
>    {'name':'Guido', 'country':'the Netherlands'}
>    >>> print s.match('Spam was born as a canned ham')
>    None


You can basically do this using regular expressions; it's not as  
"pretty", but it does exactly the same thing:

 >>> s = re.compile('(?P<name>.*) was born in (?P<country>.*)')
 >>> print s.match( 'Guido was born in the Netherlands').groupdict()
{'country': 'the Netherlands', 'name': 'Guido'}
 >>> print s.match('Spam was born as a canned ham')
None

And if you wanted non-greedy, just replace ".*" with ".*?".

Jared



More information about the Python-ideas mailing list