【问题标题】:Validating Youtube Playlist URL using Regex使用正则表达式验证 Youtube 播放列表 URL
【发布时间】:2011-03-13 11:01:01
【问题描述】:

如何使用正则表达式验证 youtube 播放列表 url?
我从其他问题中找到了验证视频的答案..
/^http:\/\/(?:www\.)?youtube.com\/watch\?(?=.*v=\w+)(?:\S+)?$/

但我无法验证这样的网址:
http://www.youtube.com/watch?list=PL1F9CA2A03CF286C2&v=pFS4zYWxzNA&

http://www.youtube.com/watch?v=pFS4zYWxzNA&list=PL1F9CA2A03CF286C2&

【问题讨论】:

    标签: regex url


    【解决方案1】:

    我最终得到了一个相似但不同的东西:

     /^.*(youtu.be\/|list=)([^#\&\?]*).*/
    

    针对以下网址工作:

    给定以下代码:

            var regExp = /^.*(youtu.be\/|list=)([^#\&\?]*).*/;
            var match = url.match(regExp);
            if (match && match[2]){
                return match[2];
            }
            return null;
    

    我的回报是 PLBOh8f9FoHHjOz0vGrD20WcTtJar-LOrw

    【讨论】:

      【解决方案2】:

      试试这个

      ^(https|http):\/\/(?:www\.)?youtube\.com\/watch\? #you forgot to mask the dot before com
      (                                         #may lead to wrong parsing
          (v=.*&list=.*)| #v and then list
          (list=.*&v=.*)  #or versa verse - feel free to use better matching
      )                   #for ids like "pFS4zYWxzNA"
      (&.*)*$             #all other kinds of parameter
      

      编辑: 我改进了匹配

      ^(https|http):\/\/(?:www\.)?youtube\.com\/watch\?
      (?:&.*)*                         #extra params at the beginning
      (
          (?:
               v=([a-zA-Z0-9_\-]{11})     #propper mathing for id
               (?:&.*)*                #extras
               &list=([a-zA-Z0-9_\-]{18}) #list
          )
          | 
          (?:
               list=([a-zA-Z0-9_\-]{18})
               (?:&.*)*                #versa
               &v=([a-zA-Z0-9_\-]{11})
          )
      )
      (?:&.*)*                         #extras at the end
      (?:\#.*)*$                       #anchors
      

      【讨论】:

      • 是的,这个正则表达式有效。但是,最后一个捕获组将始终为空,因为每个替代项末尾的 .* 匹配字符串末尾的所有内容。此外,点的使用是不恰当的,因为它匹配在任何 URL 中都无效的空格。为了改进这一点,我会将所有点星替换为:[^&\s]* 否则,干得好。
      • @ridgerunner:我确实尝试将 .* 更改为 [^&\s]*,但它不起作用.. 我将其更改为 /^http:\/\/(?:www\.)?youtube\.com\/watch\?((v=[^&\s]*&list=[^&\s]*)|(list=[^&\s]*&v=[^&\s]*))(&[^&\s]*)*$/
      • @ridgerunner:我添加了最后一组来处理 youtuves 额外的参数,如&feature=list_related&playnext=1,另见编辑
      【解决方案3】:

      首先验证 YouTube 网址:

      ^https?\:\/\/(?:www\.youtube(?:\-nocookie)?\.com\/|m\.youtube\.com\/|youtube\.com\/)?(?:ytscreeningroom\?vi?=|youtu\.be\/|vi?\/|user\/.+\/u\/\w{1,2}\/|embed\/|watch\?(?:.*\&)?vi?=|\&vi?=|\?(?:.*\&)?vi?=)([^#\&\?\n\/<>\"']*)
      

      然后找到列表:

      [\?|&](list=)(.*)\&
      

      【讨论】:

        猜你喜欢
        • 2012-11-08
        • 2011-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-07
        • 2021-02-24
        • 1970-01-01
        相关资源
        最近更新 更多