tags:

views:

43

answers:

2

I want to add an automatic embedding feature when a YouTube URL is used (http://www.youtube.com/watch?v=VID, where VID is the video's ID).

For this, I need to check if the given URL, stored in the variable url, matches "/http:\/\/www\.youtube\.com\/watch\?v=([a-z0-9]+).*/i", then I need to strip out the VID to use it (e.g. put the VID in another variable).

How can I do this (both matching and stripping)? Thanks.


P.S. Yes, I will take care of video's where embedding is disabled.
P.P.S. No, not that kind of stripping!

A: 

If you just use the match String method with your regex, it will put the VID in the $1 variable if a match was found.

yourstring.match(/http:\/\/www\.youtube\.com\/watch\?v=([a-z0-9]+).*/i)
yourvariable = $1
Curtis Edmond
I would prefer an `if`. `if yourstring =~ /myregex(...)/; yourvar = $1; end` Every time you compare or use a regex, it will populate the `$x` globals. That means using `match` or `=~` or `!~` or other regex compare methods.
Squeegy
A: 

Using match is Python-way. So use instead:

var = str[/http:\/\/www\.youtube\.com\/watch\?v=([a-z0-9]+).*/i,1]

or

/http:\/\/www\.youtube\.com\/watch\?v=(?<var>[a-z0-9]+).*/i =~ str
Nakilon