None

Python Regular Expressions

February 28, 2010

Regular expressions are a powerful way of finding things in strings.

Python

To match a regular expression anywhere in a string, use search:

lRegEx = "\d{4}"
lMatches = re.search(lRegEx, lContestName)
if lMatches:
  raise forms.ValidationError("Contest name cannot contain a year")

To match a regular expression to the beginning of the string, use match:

lRegEx = '\s*([\d\-]+)\.?\s+([\w\(\)&\'\-\. ]+),\s*([\w\.\'\- ]+)\s*[\(,]?\s*([\d\-]+)\)?[\s,]*([\d\.]*)\s*\w*'
lMatches = re.match(lRegEx, line)
if lMatches == None:
    raise forms.ValidationError("Can't work out '%s', is there a comma missing?" % (lLineToProcess))
else:
    lPosition = lMatches.group(1).strip()

The group() function returns the value that that is in the position of the brackets in the processed string. group(1) returns the first set of brackets etc, group(0) returns the entire match.

Recommended Reading

Tags: regex python