Skip to content
Lucas Caton

Regex to match Youtube URLs (using Ruby)

Lucas Caton

Lucas Caton

@lucascaton
I've created a regular expression in order to match Youtube URLs. As Youtube URLs starts with https://youtube.com and https://youtu.be, the following regex solves the problem:
ruby
/^(?: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
But it won't match:
  • youtube.com
  • youtube.com/
  • youtube.com/watch
  • youtube.com/watch/
  • youtu.be
  • youtu.be/

Post updated at 02/10/2017, 10:00:00