Porting from javascript answer to Java version JavaScript REGEX: 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 .
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.
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.
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
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"; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With