26

Porting from javascript answer to Java version JavaScript REGEX: How do I get the YouTube video id from a URL?

Community
  • 1
  • 1
Gubatron
  • 6,222
  • 5
  • 35
  • 37

13 Answers13

42

Figured this question wasn't here for Java, in case you need to do it in Java here's a way

public static String extractYTId(String ytUrl) {
    String vId = null;
    Pattern pattern = Pattern.compile(
                     "^https?://.*(?:youtu.be/|v/|u/\\w/|embed/|watch?v=)([^#&?]*).*$", 
                     Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(ytUrl);
    if (matcher.matches()){
        vId = matcher.group(1);
    }
    return vId;
}

Works for URLs like (also for https://...)

http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Gubatron
  • 6,222
  • 5
  • 35
  • 37
  • You don't need to escape `/` in Java ore regex. Also `#` `&` are not regex metacharacters so you don't need to escape them. You only need to escape `?` but *only if it is outside of* character class `[..]` so here you don't need to. – Pshemo Jun 04 '14 at 22:02
  • I edited the answer to remove unnecessary escaping and enforced case insensitive matching. – Marcin Orlowski Jul 29 '15 at 19:24
  • 28
    This method returns null –  Oct 21 '15 at 12:45
  • does not work for `https://m.youtube.com/watch?feature=youtu.be&v=123` types of links – Singed May 31 '16 at 08:56
  • Does not work for some urls you've list, and also for `https://www.youtube.com/watch?v= 0zM4nApSvMg&feature=youtu.be` – Yuri Heupa Jun 23 '16 at 23:53
  • Does not work for url: https://www.youtube.com/watch?v=ARezg1D9Zd0 . But the code of @Roman Smoliar worked (below answer). – Aakash Sharma May 01 '20 at 18:52
  • This didn't work for me. I figured out something more from this. Please refer https://stackoverflow.com/a/66786241/10440175 – Nick Mar 24 '21 at 18:05
34

Previous answers don't work for me.. It's correct method. It works with www.youtube.com and youtu.be links.

private String getYouTubeId (String youTubeUrl) {
    String pattern = "(?<=youtu.be/|watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";
    Pattern compiledPattern = Pattern.compile(pattern);
    Matcher matcher = compiledPattern.matcher(youTubeUrl);
    if(matcher.find()){
        return matcher.group();
    } else {
        return "error";  
    }
}
Roman Smoliar
  • 1,093
  • 13
  • 15
15

Update 26 Mar 2023

Support live & shorts video

Regex

https://youtube.com/live/eLlxrBmD3H4
https://www.youtube.com/live/eLlxrBmD3H4
https://youtu.be/live/eLlxrBmD3H4

https://youtube.com/shorts/FnURdCtTvTU?feature=share

http(?:s)?:\/\/(?:m.)?(?:www\.)?youtu(?:\.be\/|(?:be-nocookie|be)\.com\/(?:watch|[\w]+\?(?:feature=[\w]+.[\w]+\&)?v=|v\/|e\/|embed\/|live\/|shorts\/|user\/(?:[\w#]+\/)+))([^&#?\n]+)

Update 21 Oct 2022

As this post getting attention from people, I am going to update to serve more cases, thanks to @Nikhil Seban for your new links, the Java code is remained thanks to guys provide code @Leap Bun @Pankaj

This regex also use match group(1), please take a look on the bottom

Regex Online Here

http(?:s)?:\/\/(?:m.)?(?:www\.)?youtu(?:\.be\/|(?:be-nocookie|be)\.com\/(?:watch|[\w]+\?(?:feature=[\w]+.[\w]+\&)?v=|v\/|e\/|embed\/|user\/(?:[\w#]+\/)+))([^&#?\n]+)
http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&amp;hl=en_US&amp;rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=pJegNopBLL8
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
https://www.youtube.com/watch?v=0zM4nApSvMg&feature=youtu.be
https://www.youtube.com/watch?v=_5BTo2oZ0SE
https://m.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE
https://m.youtube.com/watch?v=_5BTo2oZ0SE
https://www.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE&app=desktop
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=eLlxrBmD3H4

https://www.youtube.com/watch?v=DFYRQ_zQ-gk&feature=featured
https://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
https://youtube.com/watch?v=DFYRQ_zQ-gk
http://youtube.com/watch?v=DFYRQ_zQ-gk
https://youtube.com/watch?v=DFYRQ_zQ-gk
http://youtube.com/watch?v=DFYRQ_zQ-gk
https://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
https://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
https://www.youtube.com/embed/DFYRQ_zQ-gk?autoplay=1
https://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
https://youtube.com/embed/DFYRQ_zQ-gk
http://youtube.com/embed/DFYRQ_zQ-gk
http://youtube.com/embed/DFYRQ_zQ-gk
https://youtube.com/embed/DFYRQ_zQ-gk
https://youtu.be/DFYRQ_zQ-gk?t=120
https://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
https://www.youtube.com/HamdiKickProduction?v=DFYRQ_zQ-gk
https://www.youtube.com/watch?v=wz4MLJBdSpw&t=67s
http://www.youtube.com/watch?v=dQw4w9WgXcQ&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW
http://www.youtube.com/embed/dQw4w9WgXcQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
https://www.youtube.com/watch?v=EL-UCUAt8DQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ 
http://youtu.be/dQw4w9WgXcQ 
http://www.youtube.com/v/dQw4w9WgXcQ 
http://www.youtube.com/e/dQw4w9WgXcQ
http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ

https://www.youtube-nocookie.com/embed/xHkq1edcbk4?rel=0

http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&amp;hl=en_US&amp;rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg

Old post

This below code you can also use either review what I have updated or to develop new pattern.


http(?:s)?:\/\/(?:m.)?(?:www\.)?youtu(?:\.be\/|be\.com\/(?:watch\?(?:feature=youtu.be\&)?v=|v\/|embed\/|user\/(?:[\w#]+\/)+))([^&#?\n]+)

This will work for

http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&amp;hl=en_US&amp;rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=pJegNopBLL8
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
https://www.youtube.com/watch?v=0zM4nApSvMg&feature=youtu.be
https://www.youtube.com/watch?v=_5BTo2oZ0SE
https://m.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE
https://m.youtube.com/watch?v=_5BTo2oZ0SE
https://www.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE&app=desktop
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=eLlxrBmD3H4

Note: Using regex match group(1) to get ID

public static String getVideoId(@NonNull String videoUrl) {
    String videoId = "";
    String regex = PLEASE_COPY_ABOVE_REGEX_PATTERN
    Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(url);
    if(matcher.find()){
        videoId = matcher.group(1);
    }
    return videoId;
}
Tấn Nguyên
  • 1,607
  • 4
  • 15
  • 25
6

To me, for the sample links you posted, this regex looks more precise (capturing the ID to Group 1):

https?://(?:www\.)?youtu(?:\.be/|be\.com/(?:watch\?v=|v/|embed/|user/(?:[\w#]+/)+))([^&#?\n]+)

On the demo, see the capture groups in the bottom right pane. However, for the second match, not entirely sure that this is a correct ID as it looks different from the other samples—to be tweaked if needed.

In code, something like:

Pattern regex = Pattern.compile("http://(?:www\\.)?youtu(?:\\.be/|be\\.com/(?:watch\\?v=|v/|embed/|user/(?:[\\w#]+/)+))([^&#?\n]+)");
    Matcher regexMatcher = regex.matcher(subjectString);
    if (regexMatcher.find()) {
        VideoID = regexMatcher.group(1);
    } 
SpencerPark
  • 3,298
  • 1
  • 15
  • 27
zx81
  • 41,100
  • 9
  • 89
  • 105
  • Fixed yours for https `http(?:s)?://(?:www\.)?youtu(?:\.be/|be\.com/(?:watch\?v=|v/|embed/|user/(?:[\w#]+/)+))([^?\n]+)` – Ghandhikus Mar 24 '16 at 20:44
6
private fun extractVideoId(ytUrl: String?): String? {
        var videoId: String? = null
        val regex =
            "^((?:https?:)?//)?((?:www|m)\\.)?((?:youtube\\.com|youtu.be|youtube-nocookie.com))(/(?:[\\w\\-]+\\?v=|feature=|watch\\?|e/|embed/|v/)?)([\\w\\-]+)(\\S+)?\$"
        val pattern: Pattern = Pattern.compile(
            regex ,
            Pattern.CASE_INSENSITIVE
        )
        val matcher: Matcher = pattern.matcher(ytUrl)
        if (matcher.matches()) {
            videoId = matcher.group(5)
        }
        return videoId
}

The above function with regex can extract video Id from

https://www.youtube.com/watch?v=DFYRQ_zQ-gk&feature=featured
https://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
https://youtube.com/watch?v=DFYRQ_zQ-gk
http://youtube.com/watch?v=DFYRQ_zQ-gk
https://youtube.com/watch?v=DFYRQ_zQ-gk
http://youtube.com/watch?v=DFYRQ_zQ-gk
https://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
https://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
https://www.youtube.com/embed/DFYRQ_zQ-gk?autoplay=1
https://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
https://youtube.com/embed/DFYRQ_zQ-gk
http://youtube.com/embed/DFYRQ_zQ-gk
http://youtube.com/embed/DFYRQ_zQ-gk
https://youtube.com/embed/DFYRQ_zQ-gk
https://youtu.be/DFYRQ_zQ-gk?t=120
https://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
https://www.youtube.com/HamdiKickProduction?v=DFYRQ_zQ-gk
https://www.youtube.com/watch?v=wz4MLJBdSpw&t=67s
http://www.youtube.com/watch?v=dQw4w9WgXcQ&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW
http://www.youtube.com/embed/dQw4w9WgXcQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
https://www.youtube.com/watch?v=EL-UCUAt8DQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ 
http://youtu.be/dQw4w9WgXcQ 
http://www.youtube.com/v/dQw4w9WgXcQ 
http://www.youtube.com/e/dQw4w9WgXcQ
http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
Nick
  • 195
  • 1
  • 5
4

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

public static String extractYoutubeVideoId(String ytUrl) {

        String vId = null;

        String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";

        Pattern compiledPattern = Pattern.compile(pattern);
        Matcher matcher = compiledPattern.matcher(ytUrl);

        if(matcher.find()){
            vId= matcher.group();
        }
        return vId;
    }

This one works for below url's

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

https://www.youtube.com/watch?v=C7RVaSEMXNk

Hope it will help some one. Thanks

King of Masses
  • 18,405
  • 4
  • 60
  • 77
3

Using regex from Tấn Nguyên:

public String getVideoIdFromYoutubeUrl(String url){
    String videoId = null;
    String regex = "http(?:s)?:\\/\\/(?:m.)?(?:www\\.)?youtu(?:\\.be\\/|be\\.com\\/(?:watch\\?(?:feature=youtu.be\\&)?v=|v\\/|embed\\/|user\\/(?:[\\w#]+\\/)+))([^&#?\\n]+)";
    Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(url);
    if(matcher.find()){
        videoId = matcher.group(1);
    }
    return videoId;
}

Credit to Tấn Nguyên.

Leap Bun
  • 2,265
  • 5
  • 28
  • 44
0

This will work for me and simple..

public static String getVideoId(@NonNull String videoUrl) {
    String reg = "(?:youtube(?:-nocookie)?\\.com\\/(?:[^\\/\\n\\s]+\\/\\S+\\/|(?:v|e(?:mbed)?)\\/|\\S*?[?&]v=)|youtu\\.be\\/)([a-zA-Z0-9_-]{11})";
    Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(videoUrl);

    if (matcher.find())
        return matcher.group(1);
    return null;
}
saravanan
  • 1,082
  • 1
  • 15
  • 30
0

Just pass youtube link in below function , it will detect all type of youtube url

    public static String getYoutubeID(String youtubeUrl) {

    if (TextUtils.isEmpty(youtubeUrl)) {
        return "";
    }
    String video_id = "";

    String expression = "^.*((youtu.be" + "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
    CharSequence input = youtubeUrl;
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(input);
    if (matcher.matches()) {
        String groupIndex1 = matcher.group(7);
        if (groupIndex1 != null && groupIndex1.length() == 11)
            video_id = groupIndex1;
    }
    if (TextUtils.isEmpty(video_id)) {
        if (youtubeUrl.contains("youtu.be/")  ) {
            String spl = youtubeUrl.split("youtu.be/")[1];
            if (spl.contains("\\?")) {
                video_id = spl.split("\\?")[0];
            }else {
                video_id =spl;
            }

        }
    }

    return video_id;
}
0

Combining a couple of methods, to cover as many formats as possible, is recommended.

String ID1 = getYoutubeID1(url); regex 1
String ID2 = getYoutubeID2(url); regex 2
String ID3 = getYoutubeID3(url); regex 3

then, using an if/switch statement to choose a value that isn't null and is valid.

SO 80
  • 197
  • 2
  • 11
0

I actully try all the above but some times work and some times fail any way I found this may it help -- in this site

private final static String expression = "(?<=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]*";
public static String getVideoId(String videoUrl) {
        if (videoUrl == null || videoUrl.trim().length() <= 0){
            return null;
    }
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(videoUrl);
        try {
            if (matcher.find())
                return matcher.group();
        } catch (ArrayIndexOutOfBoundsException ex) {
        ex.printStackTrace();
        }
        return null;
    }

he said

This will work on two kinks of youtube video urls either direct or shared URL.

Direct url: https://www.youtube.com/watch?v=XXXXXXXXXXX

Shared url: https://youtu.be/XXXXXXXXXXX

Hassan Badawi
  • 302
  • 1
  • 10
-1

This is very similar to the link posted in your question.

String url = "https://www.youtube.com/watch?v=wZZ7oFKsKzY";
if(url.indexOf("v=") == -1) //there's no video id
    return "";
String id  = url.split("v=")[1]; //everything before the first 'v=' will be the first element, i.e. [0]
int end_of_id = id_to_end.indexOf("&"); //if there are other parameters in the url, get only the id's value
if(end_index != -1)
     id = url.substring(0, end_of_id);
return id;
sh4nkc
  • 338
  • 1
  • 9
-1

Without regex :

String url - "https://www.youtube.com/watch?v=BYrumLBuzHk"
String video_id = url.replace("https://www.youtube.com/watch?v=", "")

So now you have a video ID in string video_id.