Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for youtube links

Tags:

regex

youtube

Does someone have a regular expression that gets a link to a Youtube video (not embedded object) from (almost) all the possible ways of linking to Youtube?

I think this is a pretty common problem and I'm sure there are a lot of ways to link that.

A starting point would be:

  • http://www.youtube.com/watch?v=iwGFalTRHDA
  • http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related
  • http://youtu.be/iwGFalTRHDA
  • http://youtu.be/n17B_uFF4cA
  • http://www.youtube.com/embed/watch?feature=player_embedded&v=r5nB9u4jjy4
  • http://www.youtube.com/watch?v=t-ZRX8984sc
  • http://youtu.be/t-ZRX8984sc
  • ... please add more possible links and/or regular expressions to detect them.
like image 389
jrom Avatar asked Sep 15 '10 11:09

jrom


People also ask

What is a good regex to match a URL?

@:%_\+~#= , to match the domain/sub domain name.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

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.


2 Answers

So far I got this Regular expression working for the examples I posted, and it gets the ID on the first group:

http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)? 
like image 68
jrom Avatar answered Sep 23 '22 21:09

jrom


You can use this expression below.

(?:https?:\/\/)?(?:www\.)?youtu\.?be(?:\.com)?\/?.*(?:watch|embed)?(?:.*v=|v\/|\/)([\w\-_]+)\&? 

I'm using it, and it cover the most used URLs. I'll keep updating it on This Gist. You can test it on this tool.

like image 27
brunodles Avatar answered Sep 25 '22 21:09

brunodles