Youtube 和 Vimoe 的正则表达式 url

Regex for Youtube and Vimoe url

我想验证用户为 Youtube & Vimeo

粘贴的 url

例如:

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

也可以接受 link

试试我的代码片段,此处 youtube url 将被验证。如果有效,它将 return youtube id 否则会显示 url 无效。

同样,它会检查 vimeo url 是否有效。 (我不知道 vimeo url 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")
}