如何使用 Java 中的正则表达式从 YouTube URL 获取视频 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24048308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:52:56  来源:igfitidea点击:

How to get the video id from a YouTube URL with regex in Java

javaregexyoutube

提问by Gubatron

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

从 javascript 答案移植到 Java 版本 JavaScript REGEX:如何从 URL 获取 YouTube 视频 ID?

回答by Gubatron

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

认为这个问题不是针对 Java 的,如果您需要在 Java 中进行,这里有一种方法

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://...)

适用于 URL 之类的(也适用于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

回答by xzcvtttt

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;

回答by zx81

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

对我来说,对于您发布的示例链接,此正则表达式看起来更精确(将 ID 捕获到组 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.

演示中,查看右下窗格中的捕获组。然而,对于第二场比赛,不能完全确定这是一个正确的 ID,因为它看起来与其他样本不同——如果需要可以进行调整。

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

回答by Roman Smoliar

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

以前的答案对我不起作用..这是正确的方法。它适用于 www.youtube.com 和 youtu.be 链接。

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";  
    }
}

回答by saravanan

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;
}

回答by King of Masses

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

希望它会帮助某人。谢谢

回答by T?n Nguyên

I know this topic is old, but I get more case to get Youtube id, this is my regex

我知道这个话题很旧,但我有更多的案例来获得 Youtube id,这是我的正则表达式

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

注意:使用正则表达式匹配组(1)获取 ID

回答by Prashant Maheshwari Andro

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

只需在下面的函数中传递 youtube 链接,它就会检测所有类型的 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;
}

回答by Leap Bun

Using regex from T?n Nguyên:

使用来自 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.

归功于 T?n Nguyên。

回答by SO 80

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.

然后,使用 if/switch 语句选择一个非空且有效的值。