2017-06-28 32 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? 。因为我无法使用它。 –