Regular Expressions

The re module and provides Perl-style regular expression patterns.

For an introduction, I recommend A.M. Kuchling's howto.

Say we wish to have a program that tells us whether an email address (in its first argument) is syntactically valid.

#!/usr/bin/python
import sys, re

pattern = re.compile(r'^[\w.-]+@[\w.-]+\.[A-Z]{2,4}$', re.I)

if pattern.match(sys.argv[1]):
    print "OK"
else:
    print "Something is wrong with this email address."

Here is how you invoke the program:

$ ./regex.py guido@google.com
OK
$ ./regex.py george.whitehouse.gov
Something is wrong with this email address.