【问题标题】:Regex for Youtube and Vimoe urlYoutube 和 Vimeo 网址的正则表达式
【发布时间】:2017-12-01 18:44:59
【问题描述】:

我想验证用户为 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;
    }
}

这个正则表达式不能正常工作。它甚至接受没有https ot http的链接

【问题讨论】:

  • 您的第一个正则表达式将 http 部分包含在捕获组 () 中,后跟 ?,这使其成为可选的。所以如果你不想要那些没有协议的,我建议删除?

标签: android regex url youtube vimeo


【解决方案1】:

试试我的 sn-p,这里的 youtube url 将是 validate 。如果它是有效的,它将返回 youtube id,否则它说,url 无效。

同样,它会检查 vimeo url 是否有效。 (我不知道 vimeo url id 的样子)

希望它会奏效。我使用javascript 完成了它,您可以运行并尝试 sn-p。

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")
}

【讨论】:

  • 我看不到 type_2 和 type_3 已检查以提取视频 ID 吗?
  • 我在其中提到了各种 youtube 格式。如果你愿意,你可以试试。否则将对其进行编辑。
  • 您的代码适用于 android 吗? .因为我不能用它。
  • 您需要更改它以供您使用。正则表达式只会相同
猜你喜欢
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 2014-01-20
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 2012-03-22
  • 1970-01-01
相关资源
最近更新 更多