forked from daviddrysdale/python-phonenumbers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathre_util.py
More file actions
43 lines (39 loc) · 1.39 KB
/
Copy pathre_util.py
File metadata and controls
43 lines (39 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""Additional regular expression utilities, to make it easier to sync up
with Java regular expression code.
>>> import re
>>> from .re_util import fullmatch
>>> from .util import u
>>> string = 'abcd'
>>> r1 = re.compile('abcd')
>>> r2 = re.compile('bc')
>>> r3 = re.compile('abc')
>>> fullmatch(r1, string) # doctest: +ELLIPSIS
<_sre.SRE_Match object...>
>>> fullmatch(r2, string)
>>> fullmatch(r3, string)
>>> r = re.compile('\\d{8}|\\d{10,11}')
>>> m = fullmatch(r, '1234567890')
>>> m.end()
10
>>> r = re.compile(u('[+\uff0b\\d]'), re.UNICODE)
>>> m = fullmatch(r, u('\uff10'))
>>> m.end()
1
"""
import re
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
if __name__ == '__main__': # pragma no cover
import doctest
doctest.testmod()