正则表达式 YouTube 短裤 url javascript python

Regex YouTube shorts url javascript python

我正在制作一个用户可以 post 文本、照片和 YouTube 视频 link 的看板 我正在尝试从用户复制和粘贴的不同类型的 YouTube url 生成嵌入 url。 感谢 Whosebug 大神们,我几乎明白了,但不是 100%

我的 js 正则表达式 ajax 调用 api

const ytRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$/
...
let video = $('#post-video').val();
if (ytRegex.test(video)) {
    video = $('#post-video').val();
} else {
    video = 0;
}
...

我的 python 正则表达式

video_receive = request.form['video_give']
video_id1 = re.findall("(https?\:\/\/)?(www\.)?(youtube\.com)\/.+$", video_receive)
video_id2 = re.findall("(https?\:\/\/)?(www\.)?(youtu\.?be)\/.+$", video_receive)
video_id3 = re.findall("(https?\:\/\/)?(www\.)?(youtube\.com)\/(shorts).+$", video_receive)
    if video_id1 :
      link = video_receive.split("=")[1]
      embed = "https://www.youtube.com/embed/"
      video = embed + link
    elif video_id2:
      link = video_receive.split("/")[3]
      embed = "https://www.youtube.com/embed/"
      video = embed + link
    elif video_id3:
      link = video_receive.split("/")[4]
      embed = "https://www.youtube.com/embed/"
      video = embed + link
    else:
      video = 1

我的目标是 3 个示例类型的 yt urls 变量 video_id#

  1. https://www.youtube.com/watch?v=bjkVUaFhwno

  2. https://youtu.be/BEkxOupf9Zc

  3. https://youtube.com/shorts/UZsysDAUHAY?feature=share

1 用于桌面分享 url 用于 yt 视频和 yt 短片 2 是 yt 视频的移动份额 url 3 是 yt shorts

的移动份额 url

在我的 python 代码中, if video_id1 & elif video_id2 工作正常,但在我添加 elif video_id3 后出现问题 当我用 https://youtube.com/shorts/UZsysDAUHAY?feature=share 测试时 我的代码将 https://www.youtube.com/embed/share 存储到数据库中 if video_id1 似乎正在处理 video_id3 格式。我假设这是因为测试 url 在 share 之前有 = 并且 if video_id1.split("=") 条件。

当我从测试 url 中删除 ?feature=share 时,我的网页出现错误(POST...500(内部服务器错误))甚至没有提交给数据库to ajax调用错误。但适用于原始测试 url.

请告诉我 yt 短裤哪里出错了 url。

您用于第一个模式的正则表达式也将匹配您的短裤网址,只需先检查模式 3。