# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"""
^ # begin
\s*# some empty spaces
(?:
\+? # + symbol
\d{1,2} # country code
\s*
(?(?=\)) # if followed by parens
| # then dash not allowed
-? # else optional dash
)
)? #prefix like +380
\s*
(?:
(?P<leftparen>\()? # optional left paren
\s*
0\d\d
\s*
(?(leftparen)\)|) # right paren if and only if left paren
)? # operator code, starting with 0, optinally in parentheses
(?(?<=\)) # if preceded by parens
\s*| # then dash not allowed
\s*-?\s* # else optional dash
)
(?:
\d |
(?<=
\d
)
(?(sep)
(?P=sep)|
(?P<sep>[\-\/\ ])
)
(?=
\d
)
){5,13}
\s*# some empty spaces
$ # end
#\d\d\d (?P<separator>-?) \d\d (?P=separator) \d\d $
"""
test_str = ("SHOULD MATCH:\n"
"5344654\n"
" 5344654 \n"
"534-46-54\n"
"17189280121\n"
"+19173010176\n"
"(095)789-58-75\n"
"(095) 789-58-75\n"
"0957895875\n"
"917 229 2897\n"
"+38 (095) 5344654\n"
"53-475-34\n"
"555-1-333\n"
"1-333-484\n"
"888-333-4\n"
"(094)999-22-44\n"
"38-095-432-43-34\n"
"095-432-43-34\n"
"123456\n"
"53465\n\n"
"SHOULD NOT MATCH:\n"
"1\n"
"-1234\n"
"38-(095)-432-43-34\n"
"534-46/54\n"
"(094)999/22-44\n"
"1234--567\n"
"(345)5345654\n"
"(0955344654\n"
"095)5345654\n")
matches = re.finditer(regex, test_str, re.MULTILINE | 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