import re
regex = re.compile(r"(?:(?:https?\:\/\/)?(?:www\.)?(?:youtube|youtu)(?:(?:\.com|\.be)\/)(?:embed\/)?(?:watch\?)?(?:feature=player_embedded)?&?(?:v=)?([0-z]{11}|[0-z]{4}(?:\-|\_)[0-z]{4}|.(?:\-|\_)[0-z]{9}))")
test_str = ("http://youtube.com/watch?v=iwGFalTRHDA\n"
"http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related\n"
"https://youtube.com/iwGFalTRHDA\n"
"http://youtu.be/n17B_uFF4cA\n"
"youtube.com/iwGFalTRHDA\n"
"youtube.com/n17B_uFF4cA\n"
"http://www.youtube.com/embed/watch?feature=player_embedded&v=r5nB9u4jjy4\n"
"http://www.youtube.com/watch?v=t-ZRX8984sc\n"
"http://youtu.be/t-ZRX8984sc\n"
"http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US\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