Monday, 19 May 2014

Python 3.4 does not bring any changes to its regular expression syntax compared to previous 3.x releases. It does add one new function to the re module called fullmatch(). This function takes a regular expression and a subject string as its parameters. It returns a Match object if the regular expression can match the string entirely. It returns None if the string cannot be matched or if it can only be matched partially. This is useful when using a regular expression to validate user input. In Boolean context like an if statement, the Match object evaluates to True, while None evaluates to False.

Do note that fullmatch() will evaluate to True if the subject string is the empty string and the regular expression can find zero-length matches. A zero-length match of a zero-length string is a complete match. So if you want to check whether the user entered a sequence of digits, use \d+ rather than \d* as the regex.