import re
regex = re.compile(r"^.*(youtu.be\/|v\/|u\/\w+\/|embed|e\/|watch\?v|\?v=|\&v=)([^#\&\?]{11,11}).*", flags=re.MULTILINE)
test_str = ("http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0\n"
"http://www.youtube.com/embed/0zM3nApSvMg?rel=0\n"
"http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index\n"
"http://www.youtube.com/watch?v=0zM3nApSvMg\n"
"http://youtu.be/0zM3nApSvMg\n"
"http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s\n"
"http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/KdwsulMb8EQ\n"
"http://www.youtube.com/user/IngridMichaelsonVEVO#p/u/11/KdwsulMb8EQ\n"
"http://youtu.be/dQw4w9WgXcQ\n"
"http://www.youtube.com/embed/dQw4w9WgXcQ\n"
"http://www.youtube.com/v/dQw4w9WgXcQ\n"
"http://www.youtube.com/e/dQw4w9WgXcQ\n"
"http://www.youtube.com/watch?v=dQw4w9WgXcQ\n"
"http://www.youtube.com/?v=dQw4w9WgXcQ\n"
"http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ\n"
"http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ\n"
"http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0")
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