import re
regex = re.compile(r"(?im)\b(?:https?:\/\/)?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)\/(?:(?:\??v=?i?=?\/?)|watch\?vi?=|watch\?.*?&v=|embed\/|)([A-Z0-9_-]{11})")
test_str = ("http://youtube.com/v/tFad5gHoBjY\n"
"https://youtube.com/vi/tFad5gHoBjY\n"
"http://www.youtube.com/?v=tFad5gHoBjY\n"
"http://www.youtube.com/?vi=tFad5gHoBjY\n"
"https://www.youtube.com/watch?v=tFad5gHoBjY\n"
"youtube.com/watch?vi=tFad5gHoBjY\n"
"youtu.be/tFad5gHoBjY\n"
"http://youtu.be/qokEYBNWA_0?t=30m26s\n"
"youtube.com/v/7HCZvhRAk-M\n"
"youtube.com/vi/7HCZvhRAk-M\n"
"youtube.com/?v=7HCZvhRAk-M\n"
"youtube.com/?vi=7HCZvhRAk-M\n"
"youtube.com/watch?v=7HCZvhRAk-M\n"
"youtube.com/watch?vi=7HCZvhRAk-M\n"
"youtu.be/7HCZvhRAk-M\n"
"youtube.com/embed/7HCZvhRAk-M\n"
"http://youtube.com/v/7HCZvhRAk-M\n"
"http://www.youtube.com/v/7HCZvhRAk-M\n"
"https://www.youtube.com/v/7HCZvhRAk-M\n"
"youtube.com/watch?v=7HCZvhRAk-M&wtv=wtv\n"
"http://www.youtube.com/watch?dev=inprogress&v=7HCZvhRAk-M&feature=related\n"
"youtube.com/watch?v=7HCZvhRAk-M\n"
"http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player\n"
"http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player\n"
"http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player\n"
"http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player\n"
"http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player\n"
"http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player\n"
"http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player\n"
"http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player")
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