Skip to content

Commit

Permalink
Use re.fullmatch when available (#286)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tasssadar authored Dec 5, 2023
1 parent 1df6d7d commit dc46a8e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 14 deletions.
36 changes: 23 additions & 13 deletions python/phonenumbers/re_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
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 dc46a8e

Please sign in to comment.