Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ruby - How can I alter this regex to get the Youtube video id from a Youtube URL that doesn't specify the v parameter?

At the moment I'm using this regex to extract the video id from a Youtube URL:

url.match(/v=([^&]*)/)[1]

How can I alter this so that it will also get the video id from this Youtube URL, which has no v parameter:

http://www.youtube.com/user/SHAYTARDS#p/u/9/Xc81AajGUMU

Thanks for reading.

EDIT: I'm using ruby 1.8.7

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For Ruby 1.8.7 this will do it.

url_1 = 'http://www.youtube.com/watch?v=8WVTOUh53QY&feature=feedf'
url_2 = 'http://www.youtube.com/user/ForceD3strategy#p/a/u/0/8WVTOUh53QY'

regex = /youtube.com.*(?:/|v=)([^&$]+)/
puts url_1.match(regex)[1] # => 8WVTOUh53QY
puts url_2.match(regex)[1] # => 8WVTOUh53QY

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...