import re
regex = re.compile(r"^(?P<scheme>http(?:s)?:\/\/)?(?P<www>www\d?\.)?(?P<domain>\b(?!www\d?\.)[a-z\d\-]+(?:\.[a-z\d\-]{2,})+)(?P<port>:\d{1,5})?(?P<path>\/(?:[-a-zA-Z0-9._~!$&\'()*+,;=:@]|%[0-9a-fA-F]{2})*)*(?P<query_fragm>[?#&][\/\_\-\&\%\?\#\+\=\.:a-zA-Z\d]*)*$", flags=re.MULTILINE)
test_str = ("http://example.com\n"
"https://www.example.com\n"
"http://example.com/path\n"
"https://www.example.com/path\n"
"http://example.com/path?query=1\n"
"https://www.example.com/path?query=1\n"
"http://example.com/path#fragment\n"
"https://www.example.com/path#fragment\n"
"http://example.com:8080\n"
"https://www.example.com:8080\n"
"http://subdomain.example.com\n"
"https://www.subdomain.example.com\n"
"http://subdomain.example.com/path\n"
"https://www.subdomain.example.com/path\n"
"http://subdomain.example.com/path?query=1\n"
"https://www.subdomain.example.com/path?query=1\n"
"http://subdomain.example.com/path#fragment\n"
"https://www.subdomain.example.com/path#fragment\n"
"http://subdomain.example.com:8080\n"
"https://www.subdomain.example.com:8080\n"
"http://example.org\n"
"https://www.example.org\n"
"http://example.org/path\n"
"https://www.example.org/path\n"
"http://example.org/path?query=1\n"
"https://www.example.org/path?query=1\n"
"http://example.org/path#fragment\n"
"https://www.example.org/path#fragment\n"
"http://example.org:8080\n"
"https://www.example.org:8080\n"
"http://subdomain.example.org\n"
"https://www.subdomain.example.org\n"
"http://subdomain.example.org/path\n"
"https://www.subdomain.example.org/path\n"
"http://subdomain.example.org/path?query=1\n"
"https://www.subdomain.example.org/path?query=1\n"
"http://subdomain.example.org/path#fragment\n"
"https://www.subdomain.example.org/path#fragment\n"
"http://subdomain.example.org:8080\n"
"https://www.subdomain.example.org:8080\n"
"http://example.net\n"
"https://www.example.net\n"
"http://example.net/path\n"
"https://www.example.net/path\n"
"http://example.net/path?query=1\n"
"https://www.example.net/path?query=1\n"
"http://example.net/path#fragment\n"
"https://www.example.net/path#fragment\n"
"http://example.net:8080\n"
"https://www.example.net:8080")
matches = regex.finditer(test_str)
for match_num, match in enumerate(matches, start=1):
print(f"Match {match_num} was found at {match.start()}-{match.end()}: {match.group()}")
for group_num, group in enumerate(match.groups(), start=1):
print(f"Group {group_num} found at {match.start(group_num)}-{match.end(group_num)}: {group}")
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