YouTube ID 的正则表达式 [英] Regex for YouTube ID

查看:28
本文介绍了YouTube ID 的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看遍了,我已经看到了很多方法可以从 youtube 的 URL 中解析视频 ID,但是,它们都没有匹配 YouTube url 可能采用的所有各种格式.我试过搞乱使用前几篇文章中介绍的正则表达式,但似乎没有任何效果.

I've looked all over and I've seen many ways to parse the video ID off a URL for youtube, however, none of them have matched all the various formats the YouTube url could be in. I've tried messing with regex presented in the previous posts, but nothing seemed to work.

我发现涵盖所有各种 URL 格式的最接近的帖子是这个:如何使用正则表达式在字符串中查找所有 YouTube 视频 ID?

The closest post I found that covered all the various URL formats was this one: How do I find all YouTube video ids in a string using a regex?

但是,这不适用于:http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/FJUvudQsKCM

我正在用 Javascript 做这件事.有人可以帮忙吗?!

I'm doing this in Javascript. Can someone help?!

提前谢谢.

我正在使用的当前 URL 格式和脚本:

Current URL formats and script I am using:

var url = "http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/FJUvudQsKCM";
//var url = "http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo";
//var url = "http://youtu.be/NLqAF9hrVbY";
//var url = "http://www.youtube.com/embed/NLqAF9hrVbY";
//var url = "https://www.youtube.com/embed/NLqAF9hrVbY";
//var url = "http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US";
//var url = "http://www.youtube.com/watch?v=NLqAF9hrVbY";
//var url = "http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo";
//var url = "http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I";
//var url = "http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo";
//var url = "http://www.youtube.com/watch?v=JYArUl0TzhA&feature=featured";

var videoID = url.match(/(?:youtu.be/|youtube.com(?:/embed/|/v/|/watch?v=|/user/S+|/ytscreeningroom?v=))([w-]{10,12})/)[1];
alert(videoID);

推荐答案

这是一个重复的问题,之前已经回答过.

This is a duplicate question, and has been answered before.

我想你会发现那里的正则表达式在这里也能用.

I think you will find the regexp there will also work here.

使用 preg_match 解析 YouTube 视频 ID

编辑:我注意到它不适用于您在列表顶部的 sandalsResort URL,因此您可以将正则表达式修改为以下内容(转换为在 JS 中使用)

EDIT: I noticed that it does not work for the sandalsResort URL you have at the top of your list, so you can modify the regex to the following (converted for use in JS)

var myregexp = /(?:youtube.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu.be/)([^"&?/s]{11})/gi;

我所做的只是将 user 替换为 [^/]+

All I did was to replace user with [^/]+

ID 仍然在反向引用 1 中被捕获.

The ID is still captured in back-reference 1.

这篇关于YouTube ID 的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆