Quick little regex example - Youtube video from URL

This post is more than 2 years old.

I'm almost scared to post this. Every time I post a regex example I typically get about 200 comments showing sexier, smaller, faster examples, but at the same time, I like good (and practical) examples like this. This is why regex was built! So - what's the example? Given a simple URL with a Youtube video ID in it, how do you extract just the ID? Here's the URL:


Now - you could just treat that as a list and listLast it, but we don't know if there will ever be any additional URL parameters. What we really want is the value of "V". Here is the regex I used:


And here is a complete code template:

<cfset u = "http://www.youtube.com/watch?v=f89niPP64Hg> <cfset videoid = reReplaceNoCase(u, ".*?v=([a-z0-9\-_]+).*","\1")> <cfoutput>#u#, id=#videoid#</cfoutput>

Note that this not work with Youtube's short url version: http://youtu.be/f89niPP64Hg. For that, if I found youtu.be in the URL I'd probably just listLast with / as the delimiter.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for HERE Technologies. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com