pythonregexpython-3.xpython-2.xbackport

Backport Python 3.4's regular expression "fullmatch()" to Python 2


Python 3.4 introduced the new regex method re.fullmatch(pattern, string, flags=0).

Has anyone back-ported this new method to older Python versions?


Solution

  • To make sure that the entire string matches, you need to use the \Z end-of-string anchor:

    def fullmatch(regex, string, flags=0):
        """Emulate python-3.4 re.fullmatch()."""
        return re.match("(?:" + regex + r")\Z", string, flags=flags)
    

    The \A anchor is not necessary since re.match() already anchors the match to the start of the string.