Regex for youtube URL

后端 未结 8 1348
囚心锁ツ
囚心锁ツ 2020-11-28 09:12

I am using the following regex for validating youtube video share url\'s.

var valid = /^(http\\:\\/\\/)?(youtube\\.com|youtu\\.be)+$/;
alert         


        
相关标签:
8条回答
  • 2020-11-28 09:40

    Try this:

    ((http://)?)(www\.)?((youtube\.com/)|(youtu\.be)|(youtube)).+
    

    http://regexr.com?36o7a

    0 讨论(0)
  • 2020-11-28 09:40

    Check this pattern instead:

    r'(?i)(http.//|https.//)*[A-Za-z0-9._%+-]+\.\w+'
    
    0 讨论(0)
  • 2020-11-28 09:43

    I tried this one and it works fine for me.

    (?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'<> #]+)
    

    You can check here https://regex101.com/r/Kvk0nB/1

    0 讨论(0)
  • 2020-11-28 09:45

    I know I'm like 2 years late to the party, but I was needing to write something up anyway, and seems to fit every test case that I can throw at it. Should be able to reference the first match ($1) to get the ID. Matches the http, https, www and non-www, youtube.com, youtu.be, /watch? and /watch.php? on youtube.com (youtu.be does not use these), and it supports matching even when there are other variables in the URL string (?t= for time, ?list= for playlists, etc).

    (?:https?:\/\/)?(?:youtu\.be\/|(?:www\.|m\.)?youtube\.com\/(?:watch|v|embed)(?:\.php)?(?:\?.*v=|\/))([a-zA-Z0-9\_-]+)
    
    0 讨论(0)
  • 2020-11-28 09:46

    Based on so many other regex; this is the best I have got:

    ((http(s)?:\/\/)?)(www\.)?((youtube\.com\/)|(youtu.be\/))[\S]+
    

    Test: http://regexr.com/3bga2

    0 讨论(0)
  • 2020-11-28 09:53
    • You're missing www in your regex
    • The second \. should optional (since both youtu.be and youtube are valid)
    • + in your regex allows for one or more of (youtube\.com|youtu\.be), not one or more wild-cards
      You need to use a . to indicate a wild-card, and + to indicate you want one or more of them.

    Try:

    ^(https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\/.+$
    

    Test.

    If you want it to match URLs with or without the www., just make it optional:

    ^(https?\:\/\/)?((www\.)?youtube\.com|youtu\.?be)\/.+$
    

    If you want www.youtu.be/... to also match, put the optional www. outside the brackets:

    ^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$
    
    0 讨论(0)
提交回复
热议问题