getting the youtube id from a link

前端 未结 9 1166
清歌不尽
清歌不尽 2020-12-24 13:09

I got this code to get the youtube id from the links like www.youtube.com/watch?v=xxxxxxx

  URL youtubeURL = new URL(link);
  youtubeURL.getQuery();
         


        
9条回答
  •  时光取名叫无心
    2020-12-24 13:28

    Without knowing the complete specification for all the possible YouTube URLs, this seems to work for the examples you provided:

    //*EDIT* - fixed to hopefully support more recent youtube link styles/formats:
    (?<=watch\?v=|/videos/|/embed/|youtu.be/)[^&#?]*
    

    ... matches PjDw3azfZWI from either of these URLS:

    http://www.youtube.com/watch?v=PjDw3azfZWI#t=31m08s
    http://gdata.youtube.com/feeds/api/videos/PjDw3azfZWI
    

    You would need a little more to get that particular info if you did not know that these were from youtube, though that's a pretty quick check

    Keep in mind that if you are trying to use only the result of the getQuery() method, it will not be possible to extract the result from the http://gdata.youtube.com/feeds/api/videos/PjDw3azfZWI URL, as this URL does not have a query part to it...

    Java Example:

    Pattern rex = Pattern.compile("(?<=watch\\?v=|/videos/)[^&#]*");
    Matcher m = rex.matcher(link);
    String YouTubeVideoID = m.group();
    

提交回复
热议问题