Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Mecanik/b339e629c1020fcddbf7df5fadf305b1 to your computer and use it in GitHub Desktop.
Save Mecanik/b339e629c1020fcddbf7df5fadf305b1 to your computer and use it in GitHub Desktop.
BEST Regex for YouTube, Vimeo, Twitch, Daily Motion

BEST Regex for YouTube, Vimeo, Twitch, Daily Motion

I have been searching for regexes online to ensure that I allow only 2 type of URL's on my form (YouTube/Vimeo). However, everything I found was utter crap for my requirement.

Don't get me wrong, but in my opinion they are written so poorly and cannot cover "everything"... for example, "The correct Vimeo video id regex.": https://github.com/regexhq/vimeo-regex - it's nonsense. It cannot even cover player.vimeo.com not to mention anything else. Still, it is well indexed in Google and people find it on top results.

Before you use this regex, think about your requirements. This might not work for you in case you need/want to match the FULL URL (please, think about it... do you really need to match the FULL URL??).

So without further adue, here is what I think (and you should do):

  • If you need to JUST validate what URL a user inputs on your form, it is enough to validate just the domain. No need to match the FULL URL; this can change at any point in time and you cannot predict 100% what the user will input.
  • The regex should be small and versatile, not to mention FAST. Eating away resources (for example in a serveless envinronment) is just nonsense.
/^((?:https?:)?\/\/)?((?:www|player|m)\.)?(vimeo\.com|youtube\.com|youtu\.be|twitch\.tv|dailymotion\.com|dai\.ly).*$/m

As you can see, this is short and sweet. This will match ONLY if the URL domain is YouTube or Vimeo, etc. Execution time for 1 match is 0.0 ms.

If you need other domains, simply add them after "dai.ly".

Enjoy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment