Skip to content

Commit

Permalink
Use re.fullmatch when available
Browse files Browse the repository at this point in the history
  • Loading branch information
Tasssadar committed Nov 28, 2023
1 parent 1df6d7d commit c6c7813
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 15 deletions.
40 changes: 26 additions & 14 deletions python/phonenumbers/re_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,35 @@
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)

if __name__ == '__main__': # pragma no cover
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
import doctest

doctest.testmod()
2 changes: 1 addition & 1 deletion python/phonenumbers/re_util.pyi
Original file line number Diff line number Diff line change
@@ -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: ...

0 comments on commit c6c7813

Please sign in to comment.