Check if a string matches a regex and strip a part

2019-07-29 04:16发布

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!

标签: ruby regex url
2条回答
\"骚年 ilove
2楼-- · 2019-07-29 05:10

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
查看更多
小情绪 Triste *
3楼-- · 2019-07-29 05:20

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
查看更多
登录 后发表回答