Regex Guru

Monday, 19 May 2014

Python 3.4 adds re.fullmatch()

Filed under: Regex Libraries — Jan Goyvaerts @ 13:56

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.

2 Comments »

  1. ‘fullmatch’ returns neither True nor False, but either a match object or None, just like ‘match’ and ‘search’.

    Comment by MRAB — Friday, 30 May 2014 @ 1:58

  2. I’ve updated the article to clarify that it returns a Match object or None, which evaluate to True or False in Boolean context.

    Comment by Jan Goyvaerts — Friday, 30 May 2014 @ 14:59

TrackBack URL

Leave a comment

Note: comments are moderated, so your comment will not appear instantly.