import re
regex = re.compile(r"\b(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?:\w+:\w+@)?((?:(?:[-\w\d{1-3}]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|edu|co\.uk|ac\.uk|it|fr|tv|museum|asia|local|travel|[a-z]{2}))|((\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)(\.(\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)){3}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$ |\/.,*:;=]|%[a-f\d]{2})*)?\b", flags=re.IGNORECASE)
test_str = ("# valid\n"
"http://www.google.com\n"
"ftp://example.com\n"
"google.com\n"
"a.google.com\n"
"a.google.com/b/~user\n"
"http://www.google.com/~user\n"
"www.google.com/sdfa/asdf?f93+3234\n"
"accounts.google.com\n"
"valid.domain.com/foasdf/~23423lj\n"
"accounts.google.com/login?res=sdfs sdf\n"
"accounts.google.com\n"
"you.name\n"
"you.name/~joe\n"
"google.com/+joe\n"
"https://joe:test@test.com\n\n"
"# partial \n"
"http://joe@test.com\n\n\n"
"# invalid\n"
"not: \n"
"ftp://example\n"
"something.asfdasjdlf;\n"
"abc.def@#$90fai\n"
"something.like.this\n"
"abc.def\n\n\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