C# regex to get video id from youtube and vimeo by url C# regex to get video id from youtube and vimeo by url asp.net asp.net

C# regex to get video id from youtube and vimeo by url


I had a play around with the examples and came up with these:

Youtube: youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)Vimeo: vimeo\.com/(?:.*#|.*/videos/)?([0-9]+)

And they should match all those given. The (?: ...) means that everything inside the bracket won't be captured. So only the id should be obtained.

I'm a bit of a regex novice myself, so don't be surprised if someone else comes in here screaming not to listen to me, but hopefully these will be of help.

I find this website extremely useful in working out the patterns: http://www.regexpal.com/

Edit:

get the id like so:

string url = ""; //url goes here!Match youtubeMatch = YoutubeVideoRegex.Match(url);Match vimeoMatch = VimeoVideoRegex.Match(url);string id = string.Empty;if (youtubeMatch.Success)    id = youtubeMatch.Groups[1].Value; if (vimeoMatch.Success)    id = vimeoMatch.Groups[1].Value;

That works in plain old c#.net, can't vouch for asp.net


In case you are writing some application with view model (e.g. ASP.NET MVC):

public string YouTubeUrl { get; set; }public string YouTubeVideoId{    get    {        var youtubeMatch =            new Regex(@"youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)")            .Match(this.YouTubeUrl);        return youtubeMatch.Success ? youtubeMatch.Groups[1].Value : string.Empty;    }}


Vimeo:

vimeo\.com/(?:.*#|.*/)?([0-9]+)