.Net Wildcard Pattern Matching – 在.Net上如果使用Wildcard的Pattern matching呢?

現在寫程式時..很多人會使用Regular Expression 來做Pattern Matching
來檢查字串的值符合 pattern 所包含的模式嗎.
http://msdn.microsoft.com/zh-tw/library/swf8kaxw.aspx

VB.Net上 他有一個 LIKEOperator/運算子
可以做到這個動作

可惜如果你是使用C Sharp的話
你便要自己寫一些功能去把這些Wildcard 轉換成Regular ExpressionPattern

以下是我寫的功能

        /// This static function is used to replace the regular wild card search text pattern to Regular Express pattern
        public static string WildCardToRegexPattern(string pattern)
        {
            return "^" + Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$";
        }     

        /// This function is used to execute the wild card match which is similar to VB's LIKE function
        public static bool WildCardMatch(string input, string pattern)
        {
            // Execute pattern matching against the wild card after convert the wild card to Regular Expression pattern via WildCardToRegexPattern function
            return Regex.IsMatch(input, WildCardToRegexPattern(pattern));
        }

使用方法:

string input = "abc111";
string pattern = "*11*";

Console.WriteLine(WildCardMatch(input, pattern));

Hope you find it useful

Leave a Reply