How can I alter this regex to get the Youtube vide

2019-01-25 19:53发布

问题:

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

回答1:

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


回答2:

There's no need to use regular expression

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


回答3:

 url.match(/[^\/]+$/)[0]

should work in this case. This will match anything that follows the last slash in a string, so of course it would match a lot more than just Youtube video ids. From your question I'm inferring that you already know whether a link is a Youtube link or not (since your regex is also quite unspecific), but if you don't, try

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

Unless you're on Ruby 1.9, you can't do it in a single regex because Ruby 1.8 doesn't support lookbehind.