Validating Youtube Playlist URL using Regex

2019-07-15 10:56发布

How to validate a youtube playlist url using regex?
I've found the answer for validating video from other question..
/^http:\/\/(?:www\.)?youtube.com\/watch\?(?=.*v=\w+)(?:\S+)?$/

But I've just unable to validate a url like this :
http://www.youtube.com/watch?list=PL1F9CA2A03CF286C2&v=pFS4zYWxzNA&
or
http://www.youtube.com/watch?v=pFS4zYWxzNA&list=PL1F9CA2A03CF286C2&

标签: regex url
2条回答
一纸荒年 Trace。
2楼-- · 2019-07-15 11:34

try this

^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

Edit: i improved the matching

^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
查看更多
Bombasti
3楼-- · 2019-07-15 11:44

I ended up with a something similar but different:

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

worked against the following urls:

Given the follow code:

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

My return is PLBOh8f9FoHHjOz0vGrD20WcTtJar-LOrw

查看更多
登录 后发表回答