YouTube Video ID extrator

wordcloud

Note: This page contains a small but interesting piece of Python code which I call snippets. You can find more such codes on my Python snippets page.

Problem

You and your friends like to share YouTube links all throughout the day. You want to keep track of all the videos you watch in your own personal notepad, but you find that keeping the entire link is unnecessary. Keep the video ID (the combination of letters and numbers at the end of the link) in your notepad to slim down the URL.

Task:
Create a program that parses through a link, extracts and outputs the YouTube video ID.

Input Format:
A string containing the URL to a YouTube video. The format of the string can be in "https://www.youtube.com/watch?v=2JziSFmdOf0" or the shortened "https://youtu.be/2JziSFmdOf0" format.

Output Format:
A string containing the extracted YouTube video id.

Sample Input:
https://www.youtube.com/watch?v=2JziSFmdOf0

Sample Output:
2JziSFmdOf0

Solution

Here is my solution to the above problem. Remember that there could be more than one way to solve a problem. If you have a more efficient or concise solution, please leave a comment.

In [1]:
import re
print(re.findall('(?<=\=).*|(?<=.be/).*',input())[0])
2JziSFmdOf0

Explanation

My approach (or the algorithm)

Using RegEx, match string after "=" or ".be/".

The code

  • (?<=\=).* RegEx lookbehind for "=". ?<= is the lookbehind metacharacter.
  • (?<=.be/).* RegEx lookbehind for ".be/".
  • | RegEx pipe that works like an OR here.

The problem question is picked from SoloLearn. Here is my SoloLearn code and my SoloLearn profile page.

Last updated 2021-01-09 22:48:28.790814 IST

Comments