YouTube网址正式版 [英] YouTube url id Regex
问题描述
可能重复:
正则表达式解析youtube yid
你可能认为不是另一个一,但在这里我有一个jquery正则表达式,我觉得它在大多数网址上工作得很好,一个例子在底部:
your probably thinking not another one, but here i have a jquery regex which i find it works fine on the majority of urls accpet one example at bottom:
http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
正则表达式
/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/
但是这不能从下面的url中提取id(在此示例中id为 pa14VNsdSYM )
but this cannot extract the id from the url below (in this example the id is pa14VNsdSYM)
http://www.youtube.com/watch?feature=endscreen&NR=1&v=pa14VNsdSYM
如何使用正则表达式,我可以从上面的URL中提取id。
how can using the regex can i extract the id from urls such as the one above.
推荐答案
youtube url id始终包含11个字符数字下划线和/或短划线。这是我使用的正则表达式并且没有遇到过问题:
The youtube url id always contains 11 characters numbers underscores and/or dashes. This is the regexp i've used and haven't had issues with:
var re = /[a-zA-Z0-9\-\_]{11}/;
var youtubeurl = "http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index";
alert(youtubeurl.match(re));
编辑:此解决方案实际上不能100%工作,第一个和第二个网址会有问题,因为正则表达式匹配不是视频ID的文本。
this solution doesn't actually work 100%, the first and second url's will have issues because the regexp matches text that isn't the vid id.
编辑2:试试这个:
var re = /(\?v=|\/\d\/|\/embed\/|\/v\/|\.be\/)([a-zA-Z0-9\-\_]+)/;
var urlArr = [
"http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index",
"http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o",
"http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0",
"http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s",
"http://www.youtube.com/embed/0zM3nApSvMg?rel=0",
"http://www.youtube.com/watch?v=0zM3nApSvMg",
"http://youtu.be/0zM3nApSvMg"
];
for (var i = 0; i < urlArr.length; i++) {
alert(urlArr[i].match(re)[2]);
}
这篇关于YouTube网址正式版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!