Search code examples
javaregexparsingurlyoutube

getting the youtube id from a link


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();

basically this will get me the id easily v=xxxxxxxx

but I noticed sometime youtube links will be like this

http://gdata.youtube.com/feeds/api/videos/xxxxxx

I am getting the links from a feed so do I need to build a regex for that or theres a parser to get that for me ?


Solution

  • Tried the other ones but failed in my case - adjusted the regex to fit for my urls

    String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";
        
        Pattern compiledPattern = Pattern.compile(pattern);
        Matcher matcher = compiledPattern.matcher(url);
    
        if(matcher.find()){
            return matcher.group();
        }
    

    This one works for: (you could also implement a security check youtubeid length = 11 )

    http://www.youtube.com/embed/Woq5iX9XQhA?html5=1

    http://www.youtube.com/watch?v=384IUU43bfQ

    http://gdata.youtube.com/feeds/api/videos/xTmi7zzUa-M&whatever

    Woq5iX9XQhA

    384IUU43bfQ

    xTmi7zzUa-M