Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract YouTube ID with or without RegEx

Please let me know how to get youtube ID without going to regular expression?

Using above method following URL, didn't work

http://www.youtube.com/e/dQw4w9WgXcQ

http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ

public static String extractYTId(String youtubeUrl) {
    String video_id = "";

    try {
        if(youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) {
            String expression = "^.*((youtu.be" + "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
            //String expression = "^.*(?:youtu.be\\/|v\\/|e\\/|u\\/\\w+\\/|embed\\/|v=)([^#\\&\\?]*).*";
            CharSequence input = youtubeUrl;
            Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(input);
            if(matcher.matches()) {
                String groupIndex1 = matcher.group(7);
                if(groupIndex1 != null && groupIndex1.length() == 11)
                    video_id = groupIndex1;
            }
        }
    } catch(Exception e) {
        Log.e("YoutubeActivity", "extractYTId " + e.getMessage());
    }

    return video_id;
}

Other links working fine

http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0

​​http://www.youtube.com/embed/0zM3nApSvMg?rel=0

http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index

http://www.youtube.com/watch?v=0zM3nApSvMg

http://youtu.be/0zM3nApSvMg

http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s

http://youtu.be/dQw4w9WgXcQ

http://www.youtube.com/embed/dQw4w9WgXcQ

http://www.youtube.com/v/dQw4w9WgXcQ

http://www.youtube.com/watch?v=dQw4w9WgXcQ

​​​​http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0

like image 991
Piraba Avatar asked Feb 16 '16 14:02

Piraba


People also ask

How do I find the YouTube video ID?

The video ID will be located in the URL of the video page, right after the v= URL parameter. In this case, the URL of the video is: https://www.youtube.com/watch?v=aqz-KE-bpKQ. Therefore, the ID of the video is aqz-KE-bpKQ .

How do I extract a link from YouTube?

Locate a URL using a browser on a computerIn your browser, open YouTube. Find and click the video whose URL you want to see. The URL of the video will be in the address bar.

Will YouTube run out of IDs?

With so many videos now live on the site, some users may wonder if YouTube will ever run out of the 11-digit video IDs it uses to make each upload unique. As content creator Tom Scott explains, that won't be a problem.


1 Answers

You can use following RegEx

^(?:(?:https?:\/\/)?(?:www\.)?)?(youtube(?:-nocookie)?\.com|youtu\.be)\/.*?(?:embed|e|v|watch\?.*?v=)?\/?([a-z0-9]+)

RegEx Breakup:

  1. ^: Start of the line anchor
  2. (?:(?:https?:\/\/)?(?:www\.)?)?:
    • (?:https?:\/\/)?: Match http:// or https:// optionally
    • (?:www\.)?)?: Match www. zero or one time
  3. (youtube(?:-nocookie)?\.com|youtu\.be)\/: Match either
    • youtube.com or youtube-nocookie.com or youtu.be followed by /
  4. .*?: Lazy match. Match until the next pattern satisfies.
  5. (?:embed|e|v|watch\?.*?v=)?\/?:
    • (?:embed|e|v|watch\?.*?v=)?: Match embed or e or v or from watch? to v= or nothing
    • \/?: Match / zero or one time
  6. ([a-z0-9]+): Match one or more alphanumeric characters and add that in the captured group.

Live DemoUsing JavaScript

var regex = /^(?:(?:https?:\/\/)?(?:www\.)?)?(youtube(?:-nocookie)?\.com|youtu\.be)\/.*?(?:embed|e|v|watch\?.*?v=)?\/?([a-z0-9]+)/i;

// An array of all the youtube URLs
var youtubeLinks = [
    'http://www.youtube.com/e/dQw4w9WgXcQ',
    'http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ',
    'http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0',
    'http://www.youtube.com/embed/0zM3nApSvMg?rel=0',
    'http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index',
    'http://www.youtube.com/watch?v=0zM3nApSvMg',
    'http://youtu.be/0zM3nApSvMg',
    'http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s',
    'http://youtu.be/dQw4w9WgXcQ',
    'http://www.youtube.com/embed/dQw4w9WgXcQ',
    'http://www.youtube.com/v/dQw4w9WgXcQ',
    'http://www.youtube.com/watch?v=dQw4w9WgXcQ',
    'http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0'
];

// An object to store the results
var youtubeIds = {};

// Iterate over the youtube URLs
youtubeLinks.forEach(function(url) {
    // Get the value of second captured group to extract youtube ID
    var id = "<span class='youtubeId'>" + (url.match(regex) || [0, 0, 'No ID present'])[2] + "</span>";

    // Add the URL and the extracted ID in the result object
    youtubeIds[url] = id;
});

// Log the object in the browser console
console.log(youtubeIds);

// To show the result on the page
document.getElementById('output').innerHTML = JSON.stringify(youtubeIds, 0, 4);
.youtubeId {
    color: green;
    font-weight: bold;
}
<pre id="output"></pre>

RegEx Visualization Diagram

like image 165
Tushar Avatar answered Oct 09 '22 05:10

Tushar