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.