How can I use Regex to find the ID in a YouTube link?
I don't know the pattern for youtube hashes, but I just included "-" in the capabilities as it is not considered alpha:
import re
id = re.search('(?<=\?v\=)[\w-]+', 'http://www.youtube.com/watch?v=AIiMa2Fe-ZQ')
print id.group(0)
I edited the above because as it turns out:
>>> re.search("[\w|-]", "|").group(0)
'|'
"|" in character definition does not act as a special character, but does match "|" trumpet. My apologies.
a source to share
>>> re.search('(?<=v=)[\w-]+', 'http://www.youtube.com/watch?v=AIiMa2Fe-ZQ').group()
'AIiMa2Fe-ZQ'
\w
is the shorthand for [a-zA-Z0-9_]
in python2.x, you will have to use a flag re.A
in py3k. You pretty clearly have an extra character in this video, like a hyphen. I also removed the extra backslash with lookbehind.
a source to share
/(?:/v/|/watch\?v=|/watch#!v=)([A-Za-z0-9_-]+)/
There are three alternative YouTube formats: /v/[ID]
and the watch?v=
new AJAX- watch#!v=
This RE captures all three. Also there is a new YouTube url for custom pages which is of the form / user / [user]? Content = {complex URI} This is not captured by any regex here ...
a source to share
Use urlparse module instead of regex for things like this.
import urlparse
parsed_url = urlparse.urlparse(url)
if parsed_url.netloc.find('youtube.com') != -1 and parsed_url.path == '/watch':
video = urlparse.parse_qs(parsed_url.query).get('v', None)
if video is None:
video = urlparse.parse_qs(parsed_url.fragment.strip('!')).get('v', None)
if video is not None:
print video[0]
EDIT: Updated for the new youtube url format.
a source to share