Skip to content

Instantly share code, notes, and snippets.

@b22n
Last active August 29, 2015 14:21
Show Gist options
  • Save b22n/304b01cdd113324a0f0d to your computer and use it in GitHub Desktop.
Save b22n/304b01cdd113324a0f0d to your computer and use it in GitHub Desktop.
validate a youtube link and extract the video id
public static boolean isYoutubeLink(String link) {
link = link.trim();
if (TextUtils.isEmpty(link)) return false;
String pattern = "(http(?:s?):\\/\\/)?((?:www|m)(\\.))?youtu(?:be\\.com\\/watch\\?v=|\\.be\\/)([\\w\\-\\_]*)(&(amp;)?\u200C​[\\w\\?\u200C​=]*)?";
return link.matches(pattern);
}
public static String extractYoutubeVideoId(String link) {
link = link.trim();
if (isYoutubeLink(link)) {
Uri uri = Uri.parse(link);
String host = uri.getHost();
if (TextUtils.isEmpty(host)) {
String[] split = link.split("/");
host = split[0];
}
if (!TextUtils.isEmpty(host)) {
host = host.toLowerCase();
}
if ("youtu.be".equals(host)) {
return uri.getLastPathSegment();
} else if ("youtube.com".equals(host)) {
String last = uri.getLastPathSegment();
if (!"watch".equals(host) && !"v".equals(host) && !"attribution_link".equals(host) && !"embed".equals(host)) {
return last;
}
}
return uri.getQueryParameter("v");
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment