views:

67

answers:

2

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

A: 
 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
A: 

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
But this won't find a URL without the `v=` parameter which is what the question is about.
Tim Pietzcker
I am assuming he has already scraped his desired URL into `s`, that's the "Youtube URL" he mentioned in his question.
ghostdog74
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
Ok, I misread that you wants the url instead.
ghostdog74