Java – How to get youtube video id from URL with java

javavideoyoutube

I want to get the v=id from youtube's URL with java

Example Youtube URL formats:

http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW
http://www.youtube.com/watch?v=u8nQa1cJyX8
http://youtu.be/0zM3nApSvMg
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/KdwsulMb8EQ
http://youtu.be/dQw4w9WgXcQ http://www.youtube.com/embed/dQw4w9WgXcQ
http://www.youtube.com/v/dQw4w9WgXcQ
http://www.youtube.com/e/dQw4w9WgXcQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
http://www.youtube.com/?v=dQw4w9WgXcQ
http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
http://www.youtube.com/user/IngridMichaelsonVEVO#p/u/11/KdwsulMb8EQ
http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0

or any other youtube format what contains a video id in the url

I am Trying with that :-

  Pattern compiledPattern = Pattern.compile("(?<=v=).*?(?=&|$)",Pattern.CASE_INSENSITIVE);      
        Matcher matcher = compiledPattern.matcher(sourceUrl);
        if(matcher.find()){
            setVideoId(matcher.group());
        }

It is not working only for one URL :-

http://youtu.be/6UW3xuJinEg

Best Answer

The code below will extract the video ids for the following type of urls.

http://www.youtube.com/watch?v=dQw4w9WgXcQ&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW
http://www.youtube.com/watch?v=dQw4w9WgXcQ 
http://youtu.be/dQw4w9WgXcQ 
http://www.youtube.com/embed/dQw4w9WgXcQ
http://www.youtube.com/v/dQw4w9WgXcQ 
http://www.youtube.com/e/dQw4w9WgXcQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0

String pattern = "(?<=watch\\?v=|/videos/|embed\\/|youtu.be\\/|\\/v\\/|\\/e\\/|watch\\?v%3D|watch\\?feature=player_embedded&v=|%2Fvideos%2F|embed%\u200C\u200B2F|youtu.be%2F|%2Fv%2F)[^#\\&\\?\\n]*";

        Pattern compiledPattern = Pattern.compile(pattern);
        Matcher matcher = compiledPattern.matcher(url); //url is youtube url for which you want to extract the id.
        if (matcher.find()) {
             return matcher.group();
        }