Javascript regular expression for extracting Youtube video ids

后端 未结 4 1252
清酒与你
清酒与你 2021-01-15 05:35

The following code is used to get Youtube video ids in order to get a thumbnail image.

What is the reasoning behind the first regular expression and what is it doing

相关标签:
4条回答
  • 2021-01-15 06:07

    Ok, I did some fishing around and came accross this regex. It should suit the purpose described above.

    youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)
    

    From: C# regex to get video id from youtube and vimeo by url

    And: http://forrst.com/posts/Automatic_YouTube_Thumbnails_with_PHP_and_Regex-uta

    0 讨论(0)
  • 2021-01-15 06:14
    "[\\?&]v=([^&#]*)"
    

    explained (after reduction from a JavaScript string to a regex):

    [\?&]   # Match a ? or a & (the backslash is unnecessary here!)
    v=      # Match the literal text "v="
    (       # Capture the following into backreference no. 1:
     [^&#]* # Zero or more characters except & or #
    )       # End of capturing group.
    

    The second regex [^http://youtu.be/](.*)[^?hd=1] is very wrong.

    It probably should read

    "^http://youtu.be/(.*)(?=hd=1)"
    
    0 讨论(0)
  • 2021-01-15 06:16

    The 1st regex is checking for "?v=GItD10Joaa0" when the url is something like "youtube.com/" and the 2nd is checking for "www.youtube.com/index?feature=youtu.be" when the url is "http://www.youtube.com/index?feature=youtu.be"

    So you can simply use the 1st regex if you want to get ids from 1st url and likewise :)

    0 讨论(0)
  • 2021-01-15 06:22

    If you are referring to...

    results = url.match("[\\?&]v=([^&#]*)");
    

    Then it is matching a literal \, ? or & followed by literal v= followed by a capturing group which is capturing 0 or more of any characters that are not & or #.

    0 讨论(0)
提交回复
热议问题