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