Help with Regular Expressions

Fredrik Lundh fredrik at
Wed Aug 10 13:01:03 CEST 2005

Harlin Seritt wrote:

> I am trying to find some matches and have them put into a list when
> processing is done. I'll use a simple example like email addresses.
> My input is the following:
> wordList = ['myname1', 'myname2 at domain.tld', 'myname3 at domain.tld',
> 'myname4 at domain', 'myname5 at domain.tldx']
> My regular expression would be something like '\w\@\w\.\w' (I realize
> it could and should be more detailed but that's not the point for now).
> I would like to find out how to output the matches for this expression
> of my 'wordList' into a neat list variable. How do I get this done?

that's more of a list manipulation question than a regular expression
question, of course.  to apply a regular expression to all items in a
list, apply it to all items in a list.  a list comprehension is the shortest
way to do this:

>>> out = [word for word in wordList if re.match("\w+@\w+\.\w+", word)]
>>> out
['myname2 at domain.tld', 'myname3 at domain.tld', 'myname5 at domain.tldx']


More information about the Python-list mailing list