首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 正則表達式 Match 與 Group 類別深度理解

     編輯:關於C語言

正則表達式基礎

正則表達式可視為一種特定功能的小型程式語言,用於在文本中定位子字串。可快速分析大量文本以尋找特定字元模式、提取/編輯/替換/刪除子字串,或將提取字串加入集合。基本語法請參考「深入淺出正則表達式」系列文章。

核心類別關係

System.Text.RegularExpressions 命名空間提供支援類別,主要包括 Regex、MatchCollection、Match、GroupCollection、Group、CaptureCollection、Capture。類別關係圖如下:

正則表達式類別關係圖

提取 URL 範例

使用 Regex.Matches 尋找所有符合模式的字串:

string text = "I've found this amazing URL at https://www.sohu.com ,and then find ftp://FTP.sohu.com is better.";
string pattern = @"\b(\S+)://(\S+)\b";
MatchCollection mc = Regex.Matches(text, pattern);
foreach (Match match in mc)
{
    Console.WriteLine(match.ToString());
}
// 輸出:
// https://www.sohu.com
// ftp://FTP.sohu.com

分組功能:提取協定與網址

使用具名分組 (?<name>...) 可輕鬆提取子部分:

string pattern = @"\b(?<protocol>\S+)://(?<address>\S+)\b";
MatchCollection mc = Regex.Matches(text, pattern);
foreach (Match match in mc)
{
    GroupCollection gc = match.Groups;
    string output = "URL:" + match.Value + ";Protocol:" + gc["protocol"].Value + ";Address:" + gc["address"].Value;
    Console.WriteLine(output);
}
// 輸出:
// URL:https://www.sohu.com;Protocol:http;Address:www.sohu.com
// URL:ftp://ftp.sohu.com;Protocol:ftp;Address:FTP.sohu.com

關鍵概念

  • Match 代表一次成功的比對,包含完整比對字串與分組集合。
  • Group 代表一個分組的比對結果,GroupCollection 可透過索引或名稱存取。
  • 分組 0 永遠是整個比對字串,自訂分組從 1 開始編號。
  • 具名分組 (?<name>...) 大幅提升程式碼可讀性與維護性。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved