Reputation: 105
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?
Upvotes: 1
Views: 2015
Reputation: 132972
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
Upvotes: 6
Reputation: 151214
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
)
Upvotes: 2