How can I use Regex to find the ID in a YouTube link?

When I try to extract this video ID (AIiMa2Fe-ZQ) using a regex expression, I cannot get the dash all the letters after.

>>> id = re.search('(?<=\?v\=)\w+', 'http://www.youtube.com/watch?v=AIiMa2Fe-ZQ')
>>> print id.group(0)
>>> AIiMa2Fe

      

+2


a source to share


6 answers


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.

+1


a source


The interactivity of \ w + is used below. The word character (\ w) does not include a dash. It only includes [a-zA-Z_0-9].



[\w-]+

      

+2


a source


>>> 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.

+1


a source


/(?:/v/|/watch\?v=|/watch#!v=)([A-Za-z0-9_-]+)/

      

Explain RE

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 ...

+1


a source


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.

+1


a source


I would try this:

>>> import re
>>> a = re.compile(r'.*(\-\w+)$')
>>> a.search('http://www.youtube.com/watch?v=AIiMa2Fe-ZQ').group(1)
'-ZQ'

      

0


a source







All Articles