UtilMethods { static String extractYoutubeID(String url) { String pattern = "(?<=youtu.be/|youtube.com/watch\\?v=|/videos/|embed/)[^#&\\?]*"; Pattern compiledPattern = Pattern.compile(pattern); Matcher matcher = compiledPattern.matcher(url); if (matcher.find()) { return matcher.group(); } else { return null; } }    }
@Test public void extractYoutubeID() throws Exception { assertEquals(UtilMethods.extractYoutubeID("youtube.com/watch?v=oGHWghMfbEU"), "oGHWghMfbEU"); assertEquals(UtilMethods.extractYoutubeID("https: assertEquals(UtilMethods.extractYoutubeID("https: assertEquals(UtilMethods.extractYoutubeID("youtu.be/cfrp6qfbc2g"), "cfrp6qfbc2g"); assertEquals(UtilMethods.extractYoutubeID("youtube.com/watch?v=cfrp6qfbc2g"), "cfrp6qfbc2g"); }