2016-07-30 63 views
0

嘗試下面的代碼,但它不會處理所有的情況下,像安卓:從URL獲取youtubeVideo ID爲YouTubePlayer

1) 「https://youtu.be/zuf8A0udHrs

2)「 https://www.youtube.com/watch?v=zuf8A0udHrs

private boolean isValidUrl(String url) { 

    if (url == null) { 
     return false; 
    } 
    if (URLUtil.isValidUrl(url)) { 
     // Check host of url if youtube exists 
     Uri uri = Uri.parse(url); 
     if ("www.youtube.com".equals(uri.getHost())) { 
      return true; 
     } 
     // Other way You can check into url also like 
     //if (url.startsWith("https://www.youtube.com/")) { 
      //return true; 
     //} 
    } 
    // In other any case 
    return false; 
} 

回答

0

我認爲你可以使用正則表達式來檢查一個有效的鏈接。

String pattern = "http(?:s?):\\/\\/(?:www\\.)?youtu(?:be\\.com\\/watch\\?v=|\\.be\\/)([\\w\\-\\_]*)(&(amp;)?‌​[\\w\\?‌​=]*)?"; 
     String link1 = "https://youtu.be/zuf8A0udHrs"; 
     String link2 = "https://www.youtube.com/watch?v=zuf8A0udHrs"; 

     if(link2.matches(pattern)) { 
      System.out.println("YES"); 
     } else { 
      System.out.println("NO"); 
     }