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

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

问题描述

我看了很多,我已经看到很多方法可以解析youtube的网址上的视频ID,但是,没有一种方法可以匹配YouTube网址所能提供的各种格式。我试过搞乱了在前面的帖子中提到了正则表达式,但似乎没有任何效果。

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?!

提前使用Thanx。

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

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})\b/)[1];
alert(videoID);


推荐答案

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

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

我想你会发现regexp也可以在这里工作。

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

使用preg_match解析YouTube视频ID

编辑
我注意到它不适用于列表顶部的sandalsResort网址,因此您可以将正则表达式修改为以下内容(转换为在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\/)([^"&?\/ ]{11})/i;

我所做的只是用 [^ /] +

替换用户该ID仍在后向引用1中捕获。

The ID is still captured in back-reference 1.

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

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