Regexp in python: extract email addresses

An example of using regular expressions in python to extract the email addresses from a text file.


#!/usr/bin/env python
Description: extract email addresses from stdin to stdout
Usage example: cat whatever.txt | | sort -fu > addr.txt
import re, sys
email_pattern = re.compile('([\w\-\.]+@(\w[\w\-]+\.)+[\w\-]+)')
for line in sys.stdin:
    # there are several matches per line
    for match in email_pattern.findall(line):
        print match[0]

Posted by pierre on 8 September 2007 in python

Leave a Reply