getting the youtube id from a link

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

    Got a better solution from this link.

    Use the following method to get the videoId from the link.

    YoutubeHelper.java

    import com.google.inject.Singleton; 
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    @Singleton 
    public class YouTubeHelper { 
    
        final String youTubeUrlRegEx = "^(https?)?(://)?(www.)?(m.)?((youtube.com)|(youtu.be))/";
        final String[] videoIdRegex = { "\\?vi?=([^&]*)","watch\\?.*v=([^&]*)", "(?:embed|vi?)/([^/?]*)", "^([A-Za-z0-9\\-]*)"};
    
        public String extractVideoIdFromUrl(String url) {
            String youTubeLinkWithoutProtocolAndDomain = youTubeLinkWithoutProtocolAndDomain(url);
    
            for(String regex : videoIdRegex) {
                Pattern compiledPattern = Pattern.compile(regex);
                Matcher matcher = compiledPattern.matcher(youTubeLinkWithoutProtocolAndDomain);
    
                if(matcher.find()){
                    return matcher.group(1);
                } 
            } 
    
            return null; 
        } 
    
        private String youTubeLinkWithoutProtocolAndDomain(String url) {
            Pattern compiledPattern = Pattern.compile(youTubeUrlRegEx);
            Matcher matcher = compiledPattern.matcher(url);
    
            if(matcher.find()){
                return url.replace(matcher.group(), "");
            } 
            return url;
        } 
    } 
    

    Hope this helps.

提交回复
热议问题