How can I change this regex to get a Youtube video id from a Youtube URL that does not specify the v parameter?

I am currently using this regex to retrieve a video id from a Youtube URL:

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

How can I change this so that it also gets the video id from this Youtube URL that does not have the v parameter:

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

Thanks for reading.

EDIT: I am using ruby ​​1.8.7

+5
source share
3 answers

For Ruby 1.8.7, this will be done.

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
+12
source

No need to use regex

>> url="http://www.youtube.com/user/SHAYTARDS#p/u/9/Xc81AajGUMU"
=> "http://www.youtube.com/user/SHAYTARDS#p/u/9/Xc81AajGUMU"
>> (a = url["?v="]) ? url.split("?v=")[1] : url.split("/")[-1]
=> "Xc81AajGUMU"

>> url="http://www.youtube.com/watch?v=j5-yKhDd64s"
=> "http://www.youtube.com/watch?v=j5-yKhDd64s"
>> (a = url["?v="]) ? url.split("?v=")[1] : url.split("/")[-1]
=> "j5-yKhDd64s"
+2
source
 url.match(/[^\/]+$/)[0]

. , , , , , Youtube. , , Youtube ( ), ,

url.match(/youtube.com.*([^\/]+$)/)[1]

Ruby 1.9, , Ruby 1.8 lookbehind.

0

All Articles