YouTube 网址 ID 正则表达式 [英] YouTube url id Regex
问题描述
可能的重复:
正则表达式解析youtube yid
您可能不会想到另一个,但我在这里有一个 jquery 正则表达式,我发现它在大多数 url 上都可以正常工作,在底部有一个示例:
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% 有效,第一个和第二个 url 会有问题,因为正则表达式匹配不是 vid 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.
Edit2:试试这个:
try this one:
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 网址 ID 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!