Check if a string matches a regex and strip a part of it out for use
I w开发者_JAVA技巧ant 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!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
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
精彩评论