Check if a string matches a regex and strip a part

2019-07-29 05:09发布

问题:

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!

回答1:

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


回答2:

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


标签: ruby regex url