Regex to match Youtube URLs (using Ruby)

I created a regular expression in order to match Youtube URLs.

Currently, the most common URLs from Youtube are http://youtube.com and http://youtu.be:

/^(?:https?:\/\/)?(?:www\.)?youtu(?:\.be|be\.com)\/(?:watch\?v=)?([\w-]{10,})/

This regex will match:

  • http://youtube.com/watch?v=1234567890
  • https://youtube.com/watch?v=1234567890
  • http://www.youtube.com/watch?v=1234567890
  • http://www.youtube.com/watch?v=12345-67890
  • https://www.youtube.com/watch?v=1234567890
  • http://youtu.be/1234567890
  • https://youtu.be/1234567890
  • http://www.youtu.be/1234567890
  • https://www.youtu.be/1234567890
  • http://www.youtube.com/watch?v=1234567890&feature=context&context=G2de15aaFAAAAAAAAAAA
  • www.youtube.com/watch?v=1234567890
  • youtube.com/watch?v=1234567890
  • youtu.be/1234567890

And won’t match:

  • youtube.com
  • youtube.com/
  • youtube.com/watch
  • youtube.com/watch/
  • youtu.be
  • youtu.be/
  • http://vinibaggio.net Vinicius B. Fuentes

    Então… acho que tem um validador do próprio youtube, você passa a URL e ele valida :-)

  • http://www.lucascaton.com.br/ Catón

    Hum, interessante. Tem o link?

  • http://jpcamargo.com jao

    Acho que da pra você trocar ‘(?:s?)’ por ‘s?’

    :)

  • http://www.lucascaton.com.br/ Catón

    Verdade! Vou trocar! Thanks!

  • http://www.dhtmlcentral.com ,ich bins

    I blog often and I genuinely appreciate your content. This great article has truly peaked my interest.

    I’m going to take a note of your site and keep checking for new details about once per week. I subscribed to your RSS feed too.

  • dave

    I am using your regex and noticed that this URL is not in it: http://www.youtube.com/watch?v=YgZpL-3IVoI

    Notice the – at the end before 3lVol

  • http://www.lucascaton.com.br/ Lucas Caton

    Hey Dave, you’re right.

    I’ve just updated the post with the new regular expression.
    Also, I’ve included a new example with this pattern: with a hifen (“-“).

    Thank you.