2017-06-28 31 views
1

我想驗證由用戶粘貼的url的Youtube & Vimeo的正則表達式的Youtube和Vimoe網址

如:

m.youtube.com, youtu.be, youtube.com, vimeo.com 

也想從他們

提取 video id's

我的代碼:

if (link.contains("youtu")) { 
    String youtubeRegex = "^(http(s)??\\:\\/\\/)?((www\\.)|(m\\.))?((youtube\\.com\\/watch\\?v=)|(youtu.be\\/))([a-zA-Z0-9\\-_])+"; 
    Pattern pattern = Pattern.compile(youtubeRegex); 
    Matcher matcher = pattern.matcher(link); 
    if (matcher.find()) { 
     isValid = true; 
    } else { 
     isValid = false; 
    } 
} else if (link.contains("vimeo")) { 
    String vimeoRegex = "^https:\\/\\/?vimeo\\.com\\/(clip\\:)?(\\d+).*$"; 
    Pattern pattern = Pattern.compile(vimeoRegex); 
    Matcher matcher = pattern.matcher(link); 
    if (matcher.find()) { 
     isValid = true; 
    } else { 
     isValid = false; 
    } 
} 

此正則表達式不工作properly.It接受不https ot http

+0

你的第一個正則表達式包圍HTTP部分在捕獲組'()'後跟一個'?',這使得可選。所以如果你不想要那些沒有協議,我建議刪除'?' – LukStorms

回答

1

甚至鏈接試試我的片段,在這裏YouTube網址將會驗證。如果它是有效的,它會返回youtube id,否則它說,url無效。

同樣,它會檢查vimeo url是否有效。 (我不知道如何vimeo網址ID看起來像)

希望它會工作。我用javascript做了這個,你可以運行並嘗試一下代碼片段。

type_1 = "https://www.youtube.com/watch?v=5AaCz_2cZvQ" 
 
type_2 = "youtu.be/12312/" 
 
type_3 = "youtube.com" 
 
type_4 = "vimeo.co" 
 
get_utube_id_regex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/ 
 
if(get_utube_id_regex.exec(type_1)) { 
 
    console.log("Youtube Video ID type-1 :", get_utube_id_regex.exec(type_1)[2]) 
 
} 
 
else { 
 
    console.log("invalid Youtube URL in type 1") 
 
} 
 
if(get_utube_id_regex.exec(type_2)) { 
 
    console.log("Youtube Video ID type-2 :", get_utube_id_regex.exec(type_2)[2]) 
 
} 
 
else { 
 
    console.log("invalid Youtube URL in type 2") 
 
} 
 
if(get_utube_id_regex.exec(type_3)) { 
 
    console.log("Youtube Video ID type-3 :", get_utube_id_regex.exec(type_3)[2]) 
 
} 
 
else { 
 
    console.log("invalid Youtube URL in type 3") 
 
} 
 
if(/vimeo.com/.exec(type_4)) { 
 
    console.log(/vimeo.com/.exec(type_4)) 
 
} 
 
else { 
 
    console.log("Invalid Vimeo URL in type 4") 
 
}

+0

我看不到type_2和type_3檢查提取視頻ID? –

+0

我已經提到過各種YouTube格式。如果你想要,你可以試試它。否則會編輯它。 –

+0

您的代碼是否適用於Android? 。因爲我無法使用它。 –