Backport Python 3.4的正则表达式"fullmatch()"到Python 2

ank*_*tis 10 python regex backport python-2.x python-3.x

Python 3.4引入了新的正则表达式方法re.fullmatch(pattern, string, flags=0).

有没有人将这种新方法反向移植到旧的Python版本?

Tim*_*ker 18

要确保整个字符串匹配,您需要使用\Z 字符串结束锚点:

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

\A锚是没有必要的,因为re.match()已经锚定匹配字符串的开始.