returning regex matches as lists

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Feb 15 20:17:49 EST 2008


En Fri, 15 Feb 2008 17:07:21 -0200, Jonathan Lukens  
<jonathan.lukens at gmail.com> escribió:

> I am in the last phase of building a Django app based on something I
> wrote in Java a while back.  Right now I am stuck on how to return the
> matches of a regular expression as a list *at all*, and in particular
> given that the regex has a number of groupings.  The only method I've
> seen that returns a list is .findall(string), but then I get back the
> groups as tuples, which is sort of a problem.

Do you want something like this?

py> re.findall(r"([a-z]+)([0-9]+)", "foo bar3 w000 no abc123")
[('bar', '3'), ('w', '000'), ('abc', '123')]
py> re.findall(r"(([a-z]+)([0-9]+))", "foo bar3 w000 no abc123")
[('bar3', 'bar', '3'), ('w000', 'w', '000'), ('abc123', 'abc', '123')]
py> groups = re.findall(r"(([a-z]+)([0-9]+))", "foo bar3 w000 no abc123")
py> groups
[('bar3', 'bar', '3'), ('w000', 'w', '000'), ('abc123', 'abc', '123')]
py> [group[0] for group in groups]
['bar3', 'w000', 'abc123']

-- 
Gabriel Genellina




More information about the Python-list mailing list