import re
regex = re.compile(r"^(http(s)?:\/\/)?(www.)?([a-zA-Z0-9])+([\-\.]{1}[a-zA-Z0-9]+)*\.[a-zA-Z]{2,5}(:[0-9]{1,5})?(\/[^\s]*)?$", flags=re.MULTILINE)
test_str = ("// valid urls\n"
"https://www.google.com\n"
"http://www.google.com\n"
"http://google.com/\n"
"https://google.com/\n"
"www.google.com\n"
"google.com\n"
"https://www.google.com.ua\n"
"http://www.google.com.ua\n"
"http://google.com.ua\n"
"https://google.com.ua/\n"
"www.google.com.ua\n"
"google.com.ua\n"
"https://mail.google.com\n"
"http://mail.google.com\n"
"mail.google.com\n"
"Google.com\n"
"https://google.com.adaf/:%&<>\\\\%*&~ա\\\\\n"
"foo.ama.aa/a\\sf\\\\\n\n"
"// invalid urls\n"
"http://google\n"
"https://google.c\n"
"google\n"
"google.\n"
".google\n"
".google.com\n"
"goole.c\n"
"https://google.com/ asd asdasd\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