標籤:style blog color io 使用 ar sp div on
使用Regex類需要引用命名空間:using System.Text.RegularExpressions;利用Regex類實現驗證樣本1:注釋的代碼所起的作用是相同的,不過一個是靜態方法,一個是執行個體方法var source = "劉備關羽張飛孫權"; //Regex regex = new Regex("孫權"); //if (regex.IsMatch(source)) //{ // Console.WriteLine("字串中包含有敏感詞:孫權!"); //}if (Regex.IsMatch(source, "孫權")) { Console.WriteLine("字串中包含有敏感詞:孫權!"); }Console.ReadLine();樣本2:使用帶兩個參數的建構函式,第二個參數指示忽略大小寫,很常用var source = "123abc345DEf"; Regex regex = new Regex("def",RegexOptions.IgnoreCase); if (regex.IsMatch(source)) { Console.WriteLine("字串中包含有敏感詞:def!"); } Console.ReadLine(); 使用Regex類進行替換樣本1:簡單情況var source = "123abc456ABC789"; // 靜態方法//var newSource=Regex.Replace(source,"abc","|",RegexOptions.IgnoreCase); // 執行個體方法Regex regex = new Regex("abc", RegexOptions.IgnoreCase); var newSource = regex.Replace(source, "|"); Console.WriteLine("原字串:"+source); Console.WriteLine("替換後的字串:" + newSource); Console.ReadLine();結果:原字串:123abc456ABC789替換後的字串:123|456|789 樣本2:將匹配到的選項替換為html代碼,我們使用了MatchEvaluator委託var source = "123abc456ABCD789"; Regex regex = new Regex("[A-Z]{3}", RegexOptions.IgnoreCase); var newSource = regex.Replace(source,new MatchEvaluator(OutPutMatch)); Console.WriteLine("原字串:"+source); Console.WriteLine("替換後的字串:" + newSource); Console.ReadLine(); private static string OutPutMatch(Match match) { return "<b>" +match.Value+ "</b>"; }輸出:原字串:123abc456ABCD789替換後的字串:123<b>abc</b>456<b>ABC</b>D789
C# Regex類用法