C# Regex類用法

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.