# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"""
[+]?(?<!\d)(?<!\d[ -])
(?:
((\d{1,2}[ -]?)?[(]?\d{3}[)]?[ -]?)
(\d(?:[ -]?\d){3,6})
)(?![ -]?\d)
"""
test_str = ("Matches:\n"
"--------\n"
" 1234567 123 45 67 123-45-67 \n"
" 123456789012 12 345 678 9012 12-345-678-90-12 \n"
" 1 234 56 78 912 1 234 56 789 12 1 234 567 8 901 \n"
" +1234567 \n"
" +1234567890 +12-234 561 78 90 +12 234-561-78-90\n"
" +123456789012 \n"
" +1 234 561 78 90 \n"
" 1(234)567-89-01 \n"
" (495)1234567 (495) 123 45 67 \n"
" +33 (014)-020 53 17\n\n"
"Doesn't match: \n"
"--------------\n"
" +123456 -- to short\n"
" +1234567890123 -- too long\n"
" 123 4567890123 -- too long")
matches = re.finditer(regex, test_str, re.VERBOSE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html