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

前端 未结 3 1998

I\'m busy trying to create two regular expressions to filter the id from youtube and vimeo video\'s. I\'ve already got the following expressions;

YouTube: (y         


        
相关标签:
3条回答
  • 2020-12-02 14:04

    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

    0 讨论(0)
  • 2020-12-02 14:05

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-02 14:20

    Vimeo:

    vimeo\.com/(?:.*#|.*/)?([0-9]+)
    
    0 讨论(0)
提交回复
热议问题