向后移植Python 3.4的正则表达式"fullmatch()".到Python 2 [英] Backport Python 3.4's regular expression "fullmatch()" to Python 2

查看:186
本文介绍了向后移植Python 3.4的正则表达式"fullmatch()".到Python 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有人将这个新方法移植到较旧的Python版本吗?

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

推荐答案

要确保整个字符串匹配,您需要使用\Z

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)

\A锚点不是必需的,因为re.match()已经将匹配项锚定到字符串的开头.

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

这篇关于向后移植Python 3.4的正则表达式"fullmatch()".到Python 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆