import re
regex = re.compile(r"^(?:(?:\w*.?:\/\/)?\w*.?\w*\-?.?\w*\/(?:embed|e|v|watch|.*\/)?\??(?:feature=\w*\.?\w*)?\&?(?:v=)?\/?)([\w\d_-]+).*", flags=re.MULTILINE)
test_str = ("http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW \n"
"http://www.youtube.com/watch?v=u8nQa1cJyX-8 \n"
"http://youtu.be/0zM3nApSvMg\n"
"http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/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.com/user/IngridMichaelsonVEVO#p/u/11/KdwsulMb8EQ \n"
"http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0\n"
"https://m.youtube.com/watch?feature=youtu.be&v=ROkXM3csNWY\n"
"https://www.youtube.com/watch?v=rie69P0W668\n"
"https://m.youtube.com/watch?feature=youtu.be&v=JqyzwbpYYqc\n"
"https://www.youtube.com/watch?v=YPln3JP_gKs&feature=youtu.be\n"
"https://www.youtube.com/watch?v=l-kX8Z4u0Kw&list=PLhml-dmiPOedRDLV8n1ro_OTdzKjOdlyp")
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