import re
regex = re.compile(r"(?<scheme>\w+):\/\/((?<user>\w+)(\:(?<password>[^\/:]+))?@)?(?<hostname>[\w-.]+)(:(?<port>\d+))?\/(?<request>(?<path>[^#\s\?]+)(\?(?<query>[^#\s]+))?(#(?<fragment>[^#\s]+))?)?")
test_str = ("https://example.org/absolute/URI/with/absolute/path/to/resource.txt\n"
"https://example.org/absolute/URI/with/absolute/path/to/resource.txt?a=alpha&b=bravo#bookmark\n"
"https://username:password@example.org:443/absolute/URI/with/absolute/path/to/resource.txt?a=alpha&b=bravo#bookmark\n"
"ftp://example.org/resource.txt\n"
"ftp://johndoe@example.org/resource.txt\n"
"ftp://janedoe:pa$$word@example.org/resource.txt\n"
"urn:ISSN:1535–3613\n"
"https://example.org/absolute/URI/with/absolute/path/to/resource.txt\n"
"https://username@example.org:443/absolute/URI/with/absolute/path/to/resource.txt?a=alpha&b=bravo#bookmark\n"
"https://username:password@example.org/absolute/URI/with/absolute/path/to/resource.txt?a=alpha&b=bravo#bookmark\n"
"https://username:pa$$w0rd@example.org:443/absolute/URI/with/absolute/path/to/resource.txt?a=alpha&b=bravo\n"
"//example.org/scheme-relative/URI/with/absolute/path/to/resource.txt\n"
"https://username:pa$$w0rd@example.org:443/absolute/URI/with/absolute/path/to/resource.txt#chap01\n"
"relative/path/to/resource.txt\n"
"../../../resource.txt\n"
"./resource.txt#frag01\n"
"resource.txt\n"
"#frag01\n")
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