Regex Pattern to Get the Youtube Video Id from Any Youtube Url

How do I get the YouTube video ID from a URL?

You don't need to use a regular expression for this.

var video_id = window.location.search.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1) {
video_id = video_id.substring(0, ampersandPosition);
}

RegEx pattern to get the YouTube video ID from any YouTube URL

if (preg_match('/youtube\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
} else if (preg_match('/youtube\.com\/embed\/([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
} else if (preg_match('/youtube\.com\/v\/([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
} else if (preg_match('/youtu\.be\/([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
}
else if (preg_match('/youtube\.com\/verify_age\?next_url=\/watch%3Fv%3D([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
} else {
// not an youtube video
}

This is what I use to extract the id from an youtube url. I think it works in all cases.

Note that at the end $values = id of the video

Regular expression for YouTube video Id

Try this:

urls = ['http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',

'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',

'http://youtu.be/6dwqZw0j_jY',

'http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be',

'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',

'http://www.youtube.com/embed/nas1rJpm7wY?rel=0',

'http://www.youtube.com/watch?v=peFZbP64dsU',

'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player',

'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',

'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',

'http://youtu.be/afa-5HQHiAs',

'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player',

'//www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0',

'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo',

'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',

'http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY',

'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0',

'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',

'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',

'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player',

'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player',

'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',

'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player']

_getVideoIdFromUrl = function (value) {

var regEx = "^(?:https?:)?//[^/]*(?:youtube(?:-nocookie)?\.com|youtu\.be).*[=/]([-\\w]{11})(?:\\?|=|&|$)";

var matches = value.match(regEx);

if (matches) {

console.log(value + "\n" + matches[1] + "\n");

}

return false;

}

urls.forEach(function(url) {

_getVideoIdFromUrl(url)

});

How to get the video id from YouTube url in mobile browser using regex in java

Try this regex:

v=([^\s&#]*)

Demo

Explanation:

  1. v= literally matches v=
  2. () capturing group , in this case group 1, whose value I want to
    capture here
  3. [^\s&#]* matches everything unless a space or & or #. & is necessary as
    the version id may not be the last parameter. # is necessary as # can be used as bookmark in a url.

You can try that :

    final String regex = "v=([^\\s&#]*)";
final String string = " https://m.youtube.com/watch?v=9tg3csrFVJw";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

if(matcher.find()) {
System.out.println(matcher.group(1));
}

Run it here

Extract youtube video ID from url with R stringr regex

You could use something like the following, but note that it's pretty heavily hard-coded to the examples you provided.

links = c("youtube.com/v/kFF0v0FQzEI", 
"youtube.com/vi/kFF0v0FQzEI",
"youtu.be/kFF0v0FQzEI",
"www.youtube.com/v/kFF0v0FQzEI?feature=autoshare&version=3&autohide=1&autoplay=1",
"www.youtube.com/watch?v=kFF0v0FQzEI&list=PLuV2ACKGzAMsG-pem75yNYhBvXZcl-mj_&index=1",
"youtube.com/watch?v=kFF0v0FQzEI",
"http://www.youtube.com/watch?argv=xyz&v=kFF0v0FQzEI")

get_id = function(link) {
if (stringr::str_detect(link, '/watch\\?')) {
rgx = '(?<=\\?v=|&v=)[\\w]+'
} else {
rgx = '(?<=/)[\\w]+/?(?:$|\\?)'
}
stringr::str_extract(link, rgx)
}

ids = unname(sapply(links, get_id))
# [1] "kFF0v0FQzEI" "kFF0v0FQzEI" "kFF0v0FQzEI" "kFF0v0FQzEI?"
# "kFF0v0FQzEI" "kFF0v0FQzEI" "kFF0v0FQzEI"

Get YouTube video ID from URL with Python and Regex

I don't think this (scroll right to see part denoted by ^^) is supposed to be a negative lookahead:

https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*
^^

I believe it should be a non-capturing group (i.e., ?! should be ?:).

>>> import re

>>> html = '<a href="http://www.youtube.com/watch?v=NC2blnl0WTE">Some text</a>'
>>> pattern = re.compile(r"""https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?:[?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*""", re.IGNORECASE)
>>> re.search(pattern, html).groups()
('NC2blnl0WTE',)

EDIT: Notice that I also had to use re.IGNORECASE. This is because the regex, as-is, won't match the www in www.youtube.com. You would need [0-9A-Z-] to be [0-9A-Za-z-]. However, it is safer just ignoring the case so you don't have to worry about other text in the URL.

EDIT2: As a negative lookahead, it means you would never be able to have a match when the URL is followed by the ending and closing of your anchor tag (">blah blah blah</a>).

PHP Regex to get youtube video ID?

Use parse_url() and parse_str().

(You can use regexes for just about anything, but they are very easy to make an error in, so if there are PHP functions specifically for what you are trying to accomplish, use those.)

parse_url takes a string and cuts it up into an array that has a bunch of info. You can work with this array, or you can specify the one item you want as a second argument. In this case we're interested in the query, which is PHP_URL_QUERY.

Now we have the query, which is v=C4kxS1ksqtw&feature=relate, but we only want the part after v=. For this we turn to parse_str which basically works like GET on a string. It takes a string and creates the variables specified in the string. In this case $v and $feature is created. We're only interested in $v.

To be safe, you don't want to just store all the variables from the parse_url in your namespace (see mellowsoon's comment). Instead store the variables as elements of an array, so that you have control over what variables you are storing, and you cannot accidentally overwrite an existing variable.

Putting everything together, we have:

<?php
$url = "http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
echo $my_array_of_vars['v'];
// Output: C4kxS1ksqtw
?>

Working example


Edit:

hehe - thanks Charles. That made me laugh, I've never seen the Zawinski quote before:

Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.
Jamie Zawinski



Related Topics



Leave a reply



Submit