Javascript YouTube ID 的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6903823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex for YouTube ID
提问by Stanley
I've looked all over and I've seen many ways to parse the video ID off a URL for youtube, however, none of them have matched all the various formats the YouTube url could be in. I've tried messing with regex presented in the previous posts, but nothing seemed to work.
我已经看遍了,我已经看到很多方法可以从 youtube 的 URL 解析视频 ID,但是,它们都没有匹配 YouTube url 可能采用的所有各种格式。我试过搞乱呈现的正则表达式在以前的帖子中,但似乎没有任何效果。
The closest post I found that covered all the various URL formats was this one: How do I find all YouTube video ids in a string using a regex?
我发现涵盖所有各种 URL 格式的最接近的帖子是:如何使用正则表达式在字符串中查找所有 YouTube 视频 ID?
However, this does not work for: http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/FJUvudQsKCM
但是,这不适用于:http: //www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/FJUvudQsKCM
I'm doing this in Javascript. Can someone help?!
我在 Javascript 中这样做。有人可以帮忙吗?!
Thanx in advance.
提前谢谢。
Current URL formats and script I am using:
我正在使用的当前 URL 格式和脚本:
var url = "http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/FJUvudQsKCM";
//var url = "http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo";
//var url = "http://youtu.be/NLqAF9hrVbY";
//var url = "http://www.youtube.com/embed/NLqAF9hrVbY";
//var url = "https://www.youtube.com/embed/NLqAF9hrVbY";
//var url = "http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US";
//var url = "http://www.youtube.com/watch?v=NLqAF9hrVbY";
//var url = "http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo";
//var url = "http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I";
//var url = "http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo";
//var url = "http://www.youtube.com/watch?v=JYArUl0TzhA&feature=featured";
var videoID = url.match(/(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/user\/\S+|\/ytscreeningroom\?v=))([\w\-]{10,12})\b/)[1];
alert(videoID);
回答by Benjam
This is a duplicate question, and has been answered before.
这是一个重复的问题,之前已经回答过。
I think you will find the regexp there will also work here.
我想你会发现那里的正则表达式也可以在这里工作。
parse youtube video id using preg_match
使用 preg_match 解析 youtube 视频 ID
EDIT: I noticed that it does not work for the sandalsResort URL you have at the top of your list, so you can modify the regex to the following (converted for use in JS)
编辑:我注意到它不适用于您在列表顶部的 sandalsResort URL,因此您可以将正则表达式修改为以下内容(转换为在 JS 中使用)
var myregexp = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/gi;
All I did was to replace user
with [^/]+
我所做的只是替换user
为[^/]+
The ID is still captured in back-reference 1.
ID 仍然在反向引用 1 中捕获。
回答by Maciek ?oziński
I use this regexp: /youtu(?:.*\/v\/|.*v\=|\.be\/)([A-Za-z0-9_\-]{11})/
and it works fine for me.
我使用这个正则表达式:/youtu(?:.*\/v\/|.*v\=|\.be\/)([A-Za-z0-9_\-]{11})/
它对我来说很好用。
回答by James
It would be very messy to write a single regular expression which handles all of these possible URLs.
编写一个处理所有这些可能 URL 的正则表达式会非常麻烦。
I would probably use an if ... else if ... else structure to determine which form the url is in and then use a smaller more specific regular expression to pull out each video ID.
我可能会使用 if ... else if ... else 结构来确定 url 所在的形式,然后使用更小的更具体的正则表达式来提取每个视频 ID。
回答by Justin Morgan
You probably don't need a regex for this. There is very little variance in the pattern, and the delimiters themselves (/
, and sometimes ?
, =
, or #
) are unchanging. I recommend you take this in steps, using plain old string manipulation to decide your next move:
您可能不需要为此使用正则表达式。模式中的差异很小,并且分隔符本身(/
,有时?
,=
, 或#
)是不变的。我建议您分步执行此操作,使用普通的旧字符串操作来决定您的下一步行动:
- Split the URL on
/
. - Ignore the
http://
andwww.
, if present. - Check that the domain name is
youtube.com
oryoutu.be
. - If the DN is
youtu.be
, the ID is the next segment. Return it and stop. - Start parsing parameters. Check the next segment:
- If it's
embed
, return the following segment in full. - If it's
v
, split on?
and return the first part. - If it's
user
, count four segments ahead and you'll have your ID. - If it's
watch
, split on?
and then on=
.
- If it's
- 在 上拆分 URL
/
。 - 忽略
http://
和www.
(如果存在)。 - 检查域名是否为
youtube.com
或youtu.be
。 - 如果 DN 是
youtu.be
,则 ID 是下一个段。返回并停止。 - 开始解析参数。检查下一段:
- 如果是
embed
,则完整返回以下部分。 - 如果是
v
,则拆分?
并返回第一部分。 - 如果是
user
,请数前四段,您将获得您的 ID。 - 如果是
watch
,则拆分?
然后拆分=
。
- 如果是
...etc.
...等等。
I don't know how many possible patterns there are for YouTube URLs, but if you have the full list of formats, you can simply build up an if/else tree around them. My main advice is just to split on /
and go from there, using contextual hints in the URL to determine how to parse the rest of it.
我不知道 YouTube URL 有多少可能的模式,但是如果您有完整的格式列表,您可以简单地围绕它们构建一个 if/else 树。我的主要建议是/
从那里开始拆分,使用 URL 中的上下文提示来确定如何解析它的其余部分。
回答by The Mask
Try this:
尝试这个:
var urls =
["http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/FJUvudQsKCM",
"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo",
"http://youtu.be/NLqAF9hrVbY",
"http://www.youtube.com/embed/NLqAF9hrVbY",
"https://www.youtube.com/embed/NLqAF9hrVbY",
"http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US",
"http://www.youtube.com/watch?v=NLqAF9hrVbY",
"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo",
"http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I",
"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo",
"http://www.youtube.com/watch?v=JYArUl0TzhA&feature=featured"];
var ids = [];
for(var i in urls) {
tmp = urls [ i ];
tmp2 = get_video_id(tmp);
if(tmp2 != null)
{
ids.push("url:" + tmp + " ID:" + tmp2);
}
}
alert(ids.join("\n"));
function get_video_id(input) {
return input.match(/(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/user\/\S+|\/ytscreeningroom\?v=|\/sandalsResorts#\w\/\w\/.*\/))([^\/&]{10,12})/)[1];
}
Output:
输出:
url:http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/FJUvudQsKCM ID:FJUvudQsKCM
url:http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo ID:p3vcRhsYGo
url:http://youtu.be/NLqAF9hrVbY ID:NLqAF9hrVbY
url:http://www.youtube.com/embed/NLqAF9hrVbY ID:NLqAF9hrVbY
url:https://www.youtube.com/embed/NLqAF9hrVbY ID:NLqAF9hrVbY
url:http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US ID:NLqAF9hrVbY?
url:http://www.youtube.com/watch?v=NLqAF9hrVbY ID:NLqAF9hrVbY
url:http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo ID:p3vcRhsYGo
url:http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I ID:NRHVzbJVx8I
url:http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo ID:p3vcRhsYGo
url:http://www.youtube.com/watch?v=JYArUl0TzhA&feature=featured ID:JYArUl0TzhA
回答by Kirill Artemenko
var get_id = function(url){
var code = url.match(/v=([^&#]{5,})/)
return (typeof code[1] == 'string') ? code[1] : false;
}
回答by canoodle
incorperated your regexes into this example:
将您的正则表达式合并到此示例中:
(is there actually a way of getting an array out of a text (with multiple youtube videos?)
(实际上有没有办法从文本中获取数组(有多个 youtube 视频?)
copy and paste it a file with filename: detectYoutubeLinksAsYouType.html
复制并粘贴一个文件名:detectYoutubeLinksAsYouType.html
ps: Is it only me... or is the LOGIN functionality of stackoverflow.com complete bullsh...
ps:难道只有我……还是stackoverflow.com的LOGIN功能完全废话……
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<!-- scripts -->
<!-- last jquery version that supports ie8/9 -->
<script type="text/javascript" src="../js/jquery-1.10.2.js"></script>
<script type="text/javascript">
/* search for youtube-video-id inside a given text / url */
function findYoutubeVideoID(url) {
// thanks for the regexes guys!
var YoutubeRegexObject_v1 = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i; // only gets the first VideoURL
var YoutubeRegexObject_v2 = /(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/user\/\S+|\/ytscreeningroom\?v=|\/sandalsResorts#\w\/\w\/.*\/))([^\/&]{10,12})/;
var YoutubeVideoID = url.match(YoutubeRegexObject_v1);
return YoutubeVideoID[1];
}
/* generate youtube embed code */
function generateYoutubeEmbedCode(YoutubeVideoID,width,height)
{
if(!width)
{
width = "854";
}
if(!height)
{
height = "510";
}
return '<iframe width="'+width+'" height="'+height+'" src="//www.youtube.com/embed/'+YoutubeVideoID+'" frameborder="0" allowfullscreen></iframe>';
}
$(document).ready(function() {
$("#text").on('change keyup paste', function() {
var text = $(this).html();
var YoutubeVideoID = findYoutubeVideoID(text);
var YoutubeVideoEmbedCode = generateYoutubeEmbedCode(YoutubeVideoID);
$("#findYoutubeVideoID").html(YoutubeVideoID);
$("#DisplayVideo").html(YoutubeVideoEmbedCode);
});
$("#search").on('click', function() {
var text = $("#text").html();
var YoutubeVideoID = findYoutubeVideoID(text);
var YoutubeVideoEmbedCode = generateYoutubeEmbedCode(YoutubeVideoID);
$("#findYoutubeVideoID").html(YoutubeVideoID);
$("#DisplayVideo").html(YoutubeVideoEmbedCode);
});
});
</script>
</head>
<body>
<style>
.parent {
margin: 0 auto;
position: relative;
border: 1px solid red;
width: 500px;
}
.element {
border: 1px solid red;
position: relative;
float: left;
min-height: 20px;
margin: 10px;
min-width: 45%;
}
</style>
<div class="parent">
<div class="element">Detect youtube links as you type!</div>
<div class="element" id="text" contenteditable="true">
Copy paste Youtube-Video-Url here! e.g. this one: https://www.youtube.com/watch?v=QOJ1nYPBonQ
</div>
<div class="element" >The VideoID is:</div>
<div class="element" id="findYoutubeVideoID"></div>
<div class="element" id="DisplayVideo"></div>
<div class="element"> <button id="search">Search for YoutubeID</button></div>
</div>
</body>
</html>