Need to perform Wildcard (*,?, etc) search on a string using Regex

后端 未结 10 2392
执笔经年
执笔经年 2020-11-27 04:35

I need to perform Wildcard (*, ?, etc.) search on a string. This is what I have done:

string input = \"Message\";
string pattern =          


        
10条回答
  •  余生分开走
    2020-11-27 05:02

    You need to convert your wildcard expression to a regular expression. For example:

        private bool WildcardMatch(String s, String wildcard, bool case_sensitive)
        {
            // Replace the * with an .* and the ? with a dot. Put ^ at the
            // beginning and a $ at the end
            String pattern = "^" + Regex.Escape(wildcard).Replace(@"\*", ".*").Replace(@"\?", ".") + "$";
    
            // Now, run the Regex as you already know
            Regex regex;
            if(case_sensitive)
                regex = new Regex(pattern);
            else
                regex = new Regex(pattern, RegexOptions.IgnoreCase);
    
            return(regex.IsMatch(s));
        } 
    

提交回复
热议问题