# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"^(?:[_a-z0-9](?:[_a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?)?$"
test_str = ("This regexp can be used to validate domain names in Golang. While it cannot enforce the 253 character limit (with optional trailing period not included) that can be easily done by a simple len(domain) <= 253 check as well.\n\n"
"This can be used as-is in other languages, even with RE2 regex engine. If positive lookbehind assertions are available, the character limit can be used. \n\n"
"Non-capturing groups are used.\n\n"
"Example validated domains (some may be invalid per TLD rules):\n\n"
"example.com\n"
"_25._tcp.SRV.example\n"
"punycoded-idna.xn--zckzah\n"
"under_score.example\n\n"
"Example invalid domains:\n\n"
"192.0.2.1\n"
"has spaces.com\n"
"easy,typo.example\n"
"domain\\.escapes.invalid\n"
"no_trailing_.invalid\n"
"-leading-or-trailing-.hyphens.invalid\n\n"
"TLDs have more validation, the following will not validate:\n\n"
"example\n"
"digit.1example\n"
"underscore._example_com\n\n"
"but with a trailing period, the same rules as non-TLD are applied:\n\n"
"example.\n"
"192.0.2.1.\n"
"digit.1example.\n"
"underscore._example_com.\n\n")
matches = re.finditer(regex, test_str, re.IGNORECASE | re.MULTILINE)
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