import re
regex = re.compile(r"^(http(s)?(:\/\/))?(www\.)?[a-zA-Z0-9-_\.]+(\.[a-zA-Z0-9]{2,})([-a-zA-Z0-9:%_\+.~#?&\/\/=]*)", flags=re.MULTILINE)
test_str = ("http://google.com\n"
"www.google.com\n"
"https://google.com\n"
"http://www.google.com/\n"
"http://www.google.co.th\n"
"http://www.สวสัดดีครบั.co.th\n"
"http://123.12.20.11\n"
"www.google.com\n"
"https://regex101.com/r/vM7wT6/2\n"
"https://www.google.co.th/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=regular+expression+url+ios\n\n"
"https://www.google.com\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