From e1f96325b64578ef9a80d5b419d5c40d7fd1980f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vojt=C4=9Bch=20Bo=C4=8Dek?= Date: Tue, 28 Nov 2023 13:09:02 +0100 Subject: [PATCH] Use re.fullmatch when available --- python/phonenumbers/re_util.py | 36 +++++++++++++++++++++------------ python/phonenumbers/re_util.pyi | 2 +- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/python/phonenumbers/re_util.py b/python/phonenumbers/re_util.py index 03361a0a9..2310df07e 100644 --- a/python/phonenumbers/re_util.py +++ b/python/phonenumbers/re_util.py @@ -22,21 +22,31 @@ 1 """ import re +import sys +if sys.version_info >= (3, 4): # pragma no cover -def fullmatch(pattern, string, flags=0): - """Try to apply the pattern at the start of the string, returning a match - object if the whole string matches, or None if no match was found.""" - # Build a version of the pattern with a non-capturing group around it. - # This is needed to get m.end() to correctly report the size of the - # matched expression (as per the final doctest above). - grouped_pattern = re.compile("^(?:%s)$" % pattern.pattern, pattern.flags) - m = grouped_pattern.match(string) - if m and m.end() < len(string): - # Incomplete match (which should never happen because of the $ at the - # end of the regexp), treat as failure. - m = None # pragma no cover - return m + def fullmatch(pattern, string): + """Try to apply the pattern at the start of the string, returning a match + object if the whole string matches, or None if no match was found.""" + + return pattern.fullmatch(string) + +else: + + def fullmatch(pattern, string): + """Try to apply the pattern at the start of the string, returning a match + object if the whole string matches, or None if no match was found.""" + # Build a version of the pattern with a non-capturing group around it. + # This is needed to get m.end() to correctly report the size of the + # matched expression (as per the final doctest above). + grouped_pattern = re.compile("^(?:%s)$" % pattern.pattern, pattern.flags) + m = grouped_pattern.match(string) + if m and m.end() < len(string): + # Incomplete match (which should never happen because of the $ at the + # end of the regexp), treat as failure. + m = None # pragma no cover + return m if __name__ == '__main__': # pragma no cover diff --git a/python/phonenumbers/re_util.pyi b/python/phonenumbers/re_util.pyi index 3f4efaa6d..2eefb861f 100644 --- a/python/phonenumbers/re_util.pyi +++ b/python/phonenumbers/re_util.pyi @@ -1,4 +1,4 @@ from re import Match from re import Pattern -def fullmatch(pattern: Pattern[str], string: str, flags: int = ...) -> Match[str] | None: ... +def fullmatch(pattern: Pattern[str], string: str) -> Match[str] | None: ...