掩码转换为正则表达式

   bool MatchCheck(string sn,string pattern)
        {
            return Regex.IsMatch(sn, pattern, RegexOptions.None);
        }
        
        /// <summary>
        ///  掩码转换为正则表达式
        /// </summary>
        /// <param name="msk">掩码 CTH********F2GV**</param>
        /// <param name="token">掩码符号* #</param>
        /// <returns>regexp表达式</returns>
        public static string MaskToRegex(string msk,string token)
        {
            if (string.IsNullOrEmpty(msk) || string.IsNullOrEmpty(token))
                return string.Empty;
            MatchCollection mac = Regex.Matches(msk, string.Format(@"\b(\w+)|([{0}]+)|\b",token));
            string regex = string.Empty;
            foreach (Match x in mac)
            {
                if (!string.IsNullOrEmpty(x.Value))
                {
                    if (Regex.IsMatch(x.Value, @"\w+"))
                    {
                        regex += x.Value;                        
                    }
                    if (Regex.IsMatch(x.Value, string.Format(@"[{0}]+",token)))
                    {
                        string tempmsk = string.Format(@"\w{0}", "{" + x.Value.Length + "}");                        
                        regex += tempmsk;
                    }
                }
            }
            
            string pattern = string.Format("^{0}$", regex);
            return pattern;
        }

  

原文地址:https://www.cnblogs.com/senion/p/regex.html