getting the youtube id from a link

前端 未结 9 1182
清歌不尽
清歌不尽 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:34

    This regex would do the trick:

    (?<=videos\/|v=)([\w-]+)
    

    This means that we're first looking for video/ or v= then captures all the following characters that can be in word (letters, digits, and underscores) and hyphens.

    Example in java:

    public static void main(String[] args) {
    
        String link = "http://gdata.youtube.com/feeds/api/videos/xTmi7zzUa-M&whatever";
        String pattern = "(?:videos\\/|v=)([\\w-]+)";
    
        Pattern compiledPattern = Pattern.compile(pattern);
        Matcher matcher = compiledPattern.matcher(link);
    
        if(matcher.find()){
            System.out.println(matcher.group());
        }
    }
    

    Output:

    xTmi7zzUa-M
    

提交回复
热议问题