returning regex matches as lists

John Machin sjmachin at lexicon.net
Fri Feb 15 15:25:23 EST 2008


On Feb 16, 6:07 am, Jonathan Lukens <jonathan.luk... at gmail.com> wrote:
> 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.
>

It would help if you explained what you want the contents of the list
to be, why you want a list as opposed to a tuple or a generator or
whatever ... we can't be expected to imagine why getting groups as
tuples is "sort of a problem".

Use a concrete example, e.g.

>>> import re
>>> regex = re.compile(r'(\w+)\s+(\d+)')
>>> text = 'python 1 junk xyzzy 42 java 666'
>>> r = regex.findall(text)
>>> r
[('python', '1'), ('xyzzy', '42'), ('java', '666')]
>>>

What would you like to see instead?



More information about the Python-list mailing list