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

前端 未结 2 1107
陌清茗
陌清茗 2020-12-17 19:22

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?

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-17 20:05

    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.

提交回复
热议问题