C# 正則表達式類 Match類和Group類


@"\b(\S+)://(\S+)\b"; //匹配URL的模式
foreach (Match match in mc)
{
  Console.WriteLine(match.Value);
}
Console.ReadLine();

結果:

 @"\b(?<protocol>\S+)://(?<address>\S+)\b"; //匹配URL的模式,並分組
MatchCollection mc = Regex.Matches(text, pattern); //滿足pattern的匹配集合

Console.WriteLine("文本中包含的URL地址有:");
foreach (Match match in mc)
{
  gc["protocol"].Value + ";Address:" + gc["address"].Value;
  Console.WriteLine(outputText);
}

Console.Read();

 

 

示例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=var newSource = 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 = 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