java 从链接获取 youtube id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7730328/
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-10-30 21:11:01  来源:igfitidea点击:

getting the youtube id from a link

javaregexparsingurlyoutube

提问by Peril

I got this code to get the youtube id from the links like www.youtube.com/watch?v=xxxxxxx

我得到了这个代码来从像 www.youtube.com/watch?v=xxxxxxx 这样的链接中获取 youtube id

  URL youtubeURL = new URL(link);
  youtubeURL.getQuery();

basically this will get me the id easily v=xxxxxxxx

基本上这会让我很容易得到 id v=xxxxxxxx

but I noticed sometime youtube links will be like this

但我注意到有时 youtube 链接会像这样

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 ?

我正在从提要获取链接,所以我需要为此构建一个正则表达式还是有一个解析器来为我获取它?

回答by max

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 )

这个适用于:(您也可以实施安全检查 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

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

回答by samirprogrammer

public static String getYoutubeVideoId(String youtubeUrl)
 {
 String video_id="";
  if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http"))
 {

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

回答by Marcus

This regex would do the trick:

这个正则表达式可以解决问题:

(?<=videos\/|v=)([\w-]+)

This means that we're first looking for video/or v=then captures all the following characters that can be in word (letters, digits, and underscores) and hyphens.

这意味着我们首先查找video/v=捕获以下所有可以出现在单词中的字符(字母、数字和下划线)和连字符。

Example in java:

java中的例子:

public static void main(String[] args) {

    String link = "http://gdata.youtube.com/feeds/api/videos/xTmi7zzUa-M&whatever";
    String pattern = "(?:videos\/|v=)([\w-]+)";

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

    if(matcher.find()){
        System.out.println(matcher.group());
    }
}

Output:

输出:

xTmi7zzUa-M

回答by OneCoder

That pattern worked for me:

这种模式对我有用:

"http(?:s?)://(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/)([\w\-]+)(&(amp;)?[\w\?=??]*)?"

source: Regular expression for youtube links

来源:youtube 链接的正则表达式

回答by Nabeel K

Got a better solution from this link.

从这个链接得到了一个更好的解决方案。

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

使用以下方法从链接中获取 videoId。

YoutubeHelper.java

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.

希望这可以帮助。

回答by Bahu

This was worked for me

这对我有用

public static String getYoutubeVideoId(String youtubeUrl) {
    String videoId = "";
    if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) {

        String expression = "^.*((youtu.be"+ "/)" + "|(v/)|(/u/w/)|(embed/)|(watch\?))\??v?=?([^#&\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
        Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(youtubeUrl);
        if (matcher.matches()) {
            String groupIndex1 = matcher.group(7);
            if(groupIndex1!=null && groupIndex1.length()==11)
                videoId = groupIndex1;
        }

    }
    return videoId;
}

Source link

源码链接

回答by Code Jockey

Without knowing the complete specification for all the possible YouTube URLs, this seems to work for the examples you provided:

在不知道所有可能的 YouTube URL 的完整规范的情况下,这似乎适用于您提供的示例:

//*EDIT* - fixed to hopefully support more recent youtube link styles/formats:
(?<=watch\?v=|/videos/|/embed/|youtu.be/)[^&#?]*

... matches PjDw3azfZWIfrom either of these URLS:

...PjDw3azfZWI来自以下任一网址的匹配项:

http://www.youtube.com/watch?v=PjDw3azfZWI#t=31m08s
http://gdata.youtube.com/feeds/api/videos/PjDw3azfZWI

You would need a little more to get that particular info if you did not know that these were from youtube, though that's a pretty quick check

如果您不知道这些信息来自 youtube,您将需要多一点才能获得该特定信息,尽管这是一个非常快速的检查

Keep in mind that if you are trying to use only the result of the getQuery()method, it will not be possible to extract the result from the http://gdata.youtube.com/feeds/api/videos/PjDw3azfZWIURL, as this URL does not have a query part to it...

请记住,如果您尝试仅使用该getQuery()方法的结果,则无法从http://gdata.youtube.com/feeds/api/videos/PjDw3azfZWIURL 中提取结果,因为此 URL 没有查询部分...

Java Example:

Java示例:

Pattern rex = Pattern.compile("(?<=watch\?v=|/videos/)[^&#]*");
Matcher m = rex.matcher(link);
String YouTubeVideoID = m.group();

回答by BullyWiiPlaza

This doesn't use a regex but should still do the job.

这不使用正则表达式,但仍然可以完成这项工作。

/**
 * Returns the video id of a YouTube watch link.
 */
public static String getVideoId(String watchLink)
{
    return watchLink.substring(watchLink.length() - 11);
}

回答by saravanan

This will work 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;
}