【问题标题】:Regex for YouTube ID [duplicate]YouTube ID 的正则表达式 [重复]
【发布时间】:2011-10-17 17:51:45
【问题描述】:

我已经看过了很多方法来从 youtube 的 URL 中解析视频 ID,但是,它们都没有匹配 YouTube url 可能包含的所有各种格式。我试过搞乱使用前几篇文章中介绍的正则表达式,但似乎没有任何效果。

我发现最接近所有各种 URL 格式的帖子是这个:How do I find all YouTube video ids in a string using a regex?

但是,这不适用于: http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/FJUvudQsKCM

我正在使用 Javascript 进行此操作。有人可以帮忙吗?!

提前感谢。

我正在使用的当前 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);

【问题讨论】:

  • 你可以试试get-video-id。它将从任何已知的 Youtube url 字符串(或嵌入字符串)中获取 id。
  • 在这种情况下,我将使用另一个实用程序来读取 url 参数,并跟踪 v,并为了理智删除所有 url 参数,然后测试:([\w\d_\-]+ )$/ gim regexr.com/566ho

标签: javascript regex video youtube


【解决方案1】:

这是一个重复的问题,之前已经回答过。

我想你会发现那里的正则表达式也可以在这里工作。

parse youtube video id using preg_match

编辑: 我注意到它不适用于列表顶部的 sandalsResort URL,因此您可以将正则表达式修改为以下(转换为在 JS 中使用)

var myregexp = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/gi;

我所做的只是将user 替换为[^/]+

ID 仍然在反向引用 1 中捕获。

【讨论】:

  • 谢谢.... 是的,如前所述,我发现了很多不同的正则表达式,但没有一个涵盖所有的 URL possibilites。这很好用!
  • 我在使用它从 HTML 中解析 youtube 链接时遇到了一些问题,所以我稍微更新了它:/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*?[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/gi
  • @derekantrican 这些编辑已在帖子中进行。谢谢!
  • 因为我不在乎那么多?而当我在 9 年前回答这个问题时,我没有足够的分数来关闭它。
  • 如果你想要“-nocookie”选项 /(?:youtube(?:-nocookie)?\.com\/(?:[^\/]+\/.+\/ |(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/ gi;
【解决方案2】:

将您的正则表达式合并到此示例中:

(实际上有没有办法从文本中获取数组(包含多个 youtube 视频?)

复制并粘贴一个文件名:detectYoutubeLinksAsYouType.html

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>

【讨论】:

  • 为什么我需要在登录时输入验证码?
【解决方案3】:

我使用这个正则表达式:/youtu(?:.*\/v\/|.*v\=|\.be\/)([A-Za-z0-9_\-]{11})/,它对我来说很好用。

【讨论】:

    【解决方案4】:

    您可能不需要正则表达式。模式几乎没有变化,分隔符本身(/,有时?=#)是不变的。我建议您逐步执行此操作,使用普通的旧字符串操作来决定您的下一步行动:

    1. /上拆分网址。
    2. 忽略http://www.(如果存在)。
    3. 检查域名是否为youtube.comyoutu.be
    4. 如果 DN 是 youtu.be,则 ID 是下一个段。归还并停止。
    5. 开始解析参数。检查下一段:
      • 如果是embed,则完整返回以下段。
      • 如果是v,拆分? 并返回第一部分。
      • 如果是user,数数前面的四段,您就会得到您的 ID。
      • 如果是watch,则拆分为?,然后拆分为=

    ...等等。

    我不知道 YouTube 网址有多少种可能的模式,但如果您有完整的格式列表,您可以简单地围绕它们构建一个 if/else 树。我的主要建议是拆分 / 并从那里开始,使用 URL 中的上下文提示来确定如何解析其余部分。

    【讨论】:

    • 这基本上就是get-video-id 中发生的事情。它不会尝试为所有内容维护单个 RegExp,而是将 url 模式分成组,这使得事情更容易推理。
    【解决方案5】:
    var get_id = function(url){
        var code = url.match(/v=([^&#]{5,})/)
        return (typeof code[1] == 'string') ? code[1] : false;
    }
    

    【讨论】:

      【解决方案6】:

      试试这个:

      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]; 
      }
      

      输出:

      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
      

      【讨论】:

      • 我认为问题在于“sandalsResort”部分可能不是静态的,并且会随着具有相同格式的不同 URL 发生变化。
      • Scobleizer URL 的 ID 缺少一个字符。
      【解决方案7】:

      编写一个处理所有这些可能 URL 的正则表达式会非常麻烦。

      我可能会使用 if ... else if ... else 结构来确定 url 的格式,然后使用更小更具体的正则表达式来提取每个视频 ID。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-11
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      相关资源
      最近更新 更多