Last active
August 29, 2015 14:21
-
-
Save b22n/304b01cdd113324a0f0d to your computer and use it in GitHub Desktop.
validate a youtube link and extract the video id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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