Regex pattern for checking if a string starts with a certain substring?

后端 未结 5 1104
小鲜肉
小鲜肉 2020-12-05 22:50

What\'s the regular expression to check if a string starts with \"mailto\" or \"ftp\" or \"joe\" or...

Now I am using C# and code like this in a big if with many ors

5条回答
  •  情话喂你
    2020-12-05 23:09

    For the extension method fans:

    public static bool RegexStartsWith(this string str, params string[] patterns)
    {
        return patterns.Any(pattern => 
           Regex.Match(str, "^("+pattern+")").Success);
    }
    

    Usage

    var answer = str.RegexStartsWith("mailto","ftp","joe");
    //or
    var answer2 = str.RegexStartsWith("mailto|ftp|joe");
    //or
    bool startsWithWhiteSpace = "  does this start with space or tab?".RegexStartsWith(@"\s");
    

提交回复
热议问题