Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I alter this regex to get the Youtube video id from a Youtube URL that doesn't specify the v parameter?

At the moment I'm using this regex to extract the video id from a Youtube URL:

url.match(/v=([^&]*)/)[1]

How can I alter this so that it will also get the video id from this Youtube URL, which has no v parameter:

http://www.youtube.com/user/SHAYTARDS#p/u/9/Xc81AajGUMU

Thanks for reading.

EDIT: I'm using ruby 1.8.7

like image 576
ben Avatar asked Oct 11 '10 06:10

ben


People also ask

How do I get the YouTube video ID from a URL?

The video ID will be located in the URL of the video page, right after the v= URL parameter. In this case, the URL of the video is: https://www.youtube.com/watch?v=aqz-KE-bpKQ. Therefore, the ID of the video is aqz-KE-bpKQ .

How long are YouTube video ids?

YouTube ID is a string of 11 characters, which consists of both upper and lower case alphabets and numeric values. It is used to define a YouTube video uniquely.


1 Answers

For Ruby 1.8.7 this will do it.

url_1 = 'http://www.youtube.com/watch?v=8WVTOUh53QY&feature=feedf'
url_2 = 'http://www.youtube.com/user/ForceD3strategy#p/a/u/0/8WVTOUh53QY'

regex = /youtube.com.*(?:\/|v=)([^&$]+)/
puts url_1.match(regex)[1] # => 8WVTOUh53QY
puts url_2.match(regex)[1] # => 8WVTOUh53QY
like image 57
Andrew Brown Avatar answered Oct 12 '22 23:10

Andrew Brown