Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 528
Gubatron Avatar asked Jun 04 '14 21:06

Gubatron


People also ask

How do I get the YouTube video ID from a URL?

The video ID will be located in the URL of the video page, right after the v= URL parameter. In this case, the URL of the video is: https://www.youtube.com/watch?v=aqz-KE-bpKQ. Therefore, the ID of the video is aqz-KE-bpKQ .

How do I verify a YouTube video ID?

you can hit this: http://gdata.youtube.com/feeds/api/videos/VIDEO_ID (Page now returns: "No longer available".) There's no way you can check the validity of the ID with RegEx, since not all alpha-numeric values are valid ID's.

What is the YouTube video ID?

A YouTube Video ID is a unique ID to identify a video which is uploaded to YouTube. A YouTube video ID is used to create a unique URL to show the video and can be used to embed a YouTube video on any website. It's not possible to change a video ID of a video.


2 Answers

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 
like image 61
Gubatron Avatar answered Oct 11 '22 14:10

Gubatron


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";       } } 
like image 35
Roman Smoliar Avatar answered Oct 11 '22 14:10

Roman Smoliar