5

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

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
ben
  • 29,229
  • 42
  • 124
  • 179

3 Answers3

14

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
zevstatiev
  • 113
  • 9
Andrew Brown
  • 141
  • 1
  • 3
  • This regex fails on this - `//www.youtube.com/embed/bUju90SSgSI?rel=0`. Should change regex to `regex = /youtube.com.*(?:\/|v=)([^&$\?]+)/` – Trantor Liu Jul 08 '19 at 02:53
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"
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • But this won't find a URL without the `v=` parameter which is what the question is about. – Tim Pietzcker Oct 11 '10 at 07:09
  • I am assuming he has already scraped his desired URL into `s`, that's the "Youtube URL" he mentioned in his question. – ghostdog74 Oct 11 '10 at 07:12
  • I'm assuming this too; what I meant to say was that he won't find the video ID if that URL doesn't contain a `v=` parameter (see his second example). – Tim Pietzcker Oct 11 '10 at 07:18
0
 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.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561