从链接获取 youtube id

发布于 2024-12-09 07:16:21 字数 348 浏览 1 评论 0原文

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

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

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

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

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

我从提要中获取链接 那么我是否需要为此构建一个正则表达式,或者有一个解析器来为我获取它?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

感性不性感 2024-12-16 07:16:21

尝试了其他方法,但在我的情况下失败了 - 调整正则表达式以适合我的网址

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

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

这一个适用于:(您还可以实施安全检查 youtubeid length = 11 )

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


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

http://gdata.youtube.com/feeds/api/视频/xTmi7zzUa-M&无论什么

Woq5iX9XQhA

384IUU43bfQ

xTmi7zzUa-M

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

生活了然无味 2024-12-16 07:16:21
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;
 }
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;
 }
坏尐絯℡ 2024-12-16 07:16:21

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

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

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

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

输出:

xTmi7zzUa-M

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.

Example in 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
街角迷惘 2024-12-16 07:16:21

从此链接获得了更好的解决方案。

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

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

希望这有帮助。

Got a better solution from this link.

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

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.

时光瘦了 2024-12-16 07:16:21

这种模式对我有用:

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

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

That pattern worked for me:

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

source: Regular expression for youtube links

美男兮 2024-12-16 07:16:21

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

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

...与这些 URL 中的任何一个匹配 PjDw3azfZWI

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

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

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

Java 示例:

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

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

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

... matches PjDw3azfZWI from either of these URLS:

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

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/PjDw3azfZWI URL, as this URL does not have a query part to it...

Java Example:

Pattern rex = Pattern.compile("(?<=watch\\?v=|/videos/)[^&#]*");
Matcher m = rex.matcher(link);
String YouTubeVideoID = m.group();
她说她爱他 2024-12-16 07:16:21

这对我有用

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

来源链接

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

っ〆星空下的拥抱 2024-12-16 07:16:21

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

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

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);
}
雨后咖啡店 2024-12-16 07:16:21
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;
}
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;
}
难得心□动 2024-12-16 07:16:21

这是 kotlin 版本,它将支持许多 Youtube 网址,包括Shorts

private fun getVideoId(youtubeUrl: String): String {
    var videoId = ""
    val regex = "/(?:watch|\\w+\\?(?:feature=\\w+.\\w+&)?v=|(videos/)|v/|e/|embed/|live/|shorts/|user/(?:[\\w#]+/)+)([^&#?\\n]+)"
    val pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE)
    val matcher = pattern.matcher(youtubeUrl)
    if(matcher.find()){
        videoId = matcher.group(2).orEmpty()
    }
    return videoId
}

以下是我测试过的一些示例:

https://youtube.com/watch?v=olij8GbEHJ0
www.youtube.com/watch?v=olij8GbEHJ0
https://youtu.be/shorts/fMlV1dGb1cI?feature=share
http://gdata.youtube.com/feeds/api/videos/xxxxxx
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

尝试一下regex101.com 在左侧菜单中选择 Java

Here is the kotlin version that will support many of Youtube urls including Shorts:

private fun getVideoId(youtubeUrl: String): String {
    var videoId = ""
    val regex = "/(?:watch|\\w+\\?(?:feature=\\w+.\\w+&)?v=|(videos/)|v/|e/|embed/|live/|shorts/|user/(?:[\\w#]+/)+)([^&#?\\n]+)"
    val pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE)
    val matcher = pattern.matcher(youtubeUrl)
    if(matcher.find()){
        videoId = matcher.group(2).orEmpty()
    }
    return videoId
}

Here are some samples to I've tested against:

https://youtube.com/watch?v=olij8GbEHJ0
www.youtube.com/watch?v=olij8GbEHJ0
https://youtu.be/shorts/fMlV1dGb1cI?feature=share
http://gdata.youtube.com/feeds/api/videos/xxxxxx
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

Try it on regex101.com choosing Java on the left menu

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文