C# Regex類用法


使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM