I have to extract http://www.youtube.com/watch?v=aNdMiIAlK0g the video id from this url. Anyone know how do this using gsub and regex?
Asked
Active
Viewed 1,995 times
1
-
1Someone's trying to do the same thing in [this question](http://stackoverflow.com/questions/3903854/how-can-i-alter-this-regex-to-get-the-youtube-video-id-from-a-youtube-url-that-do) – Andrew Grimm Nov 25 '10 at 11:41
-
Sometimes there could be short url like http://youtu.be/aNdMiIAlK0g which you might consider here – Amit Patel Sep 10 '14 at 10:26
2 Answers
6
You can match the v
parameter with this regexp:
url[/(?<=[?&]v=)[^&$]+/] # => aNdMiIAlK0g
It starts with a lookbehind for ?
or &
and matches everything up until the next &
or the end of the string. It works even if there are other parameters, even those ending in "v".
However, a safer way to do it might be to use the URI class:
require 'uri'
query_string = URI.parse(url).query
parameters = Hash[URI.decode_www_form(query_string)]
parameters['v'] # => aNdMiIAlK0g

Theo
- 131,503
- 21
- 160
- 205
2
this is it:
ruby-1.9.2-p0 > "http://www.youtube.com/watch?v=aNdMiIAlK0g"[/v=([^&]+)/, 1]
=> "aNdMiIAlK0g"
(although you may want to use the URI library to get the query part and split them using &
and use the value for v
, because the above will get confused if the url is something like http://www.youtube.com/promo?for_tv=1 and it will take it as v=1
)

nonopolarity
- 146,324
- 131
- 460
- 740
-
thanks man, I tryed this and got the result too : str.match(/v=([\w|-]*)&*/)[1] – Mozart Brum Nov 25 '10 at 08:42