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

C# 正則表達式深度解析(八):實用模式範例集錦

     編輯:關於C語言

常見文字處理正則模式

1. 擷取所有大寫單字

string text = "This IS a Test OF ALL Caps";
string pattern = @"(\b[^\Wa-z0-9_]+\b)";
MatchCollection matches = Regex.Matches(text, pattern);
// 結果:IS, OF, ALL, CAPS

模式解析:\b 字邊界,[^\Wa-z0-9_] 排除非單字字元、小寫、數字、底線 → 相當於只匹配大寫字母。

2. 擷取所有小寫單字

string text = "This is A Test of lowercase";
string pattern = @"(\b[^\WA-Z0-9_]+\b)";
MatchCollection matches = Regex.Matches(text, pattern);
// 結果:is, of, lowercase

3. 擷取首字母大寫的單字

string text = "This is A Test of Initial Caps";
string pattern = @"(\b[^\Wa-z0-9_][^\WA-Z0-9_]*\b)";
MatchCollection matches = Regex.Matches(text, pattern);
// 結果:This, A, Test, Initial, Caps

首字元:大寫字母;後續字元:非大寫(含小寫、數字、底線等)。

4. 解析簡單 HTML 連結

string html = @"first tag textnext tag text";
string pattern = @"]*?HREF\s*=\s*[""']?([^'"" >]+?)['""]?>";
MatchCollection matches = Regex.Matches(html, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
// Group[1] 捕獲:first.htm, next.htm

使用 Singleline 讓 . 匹配換行,IgnoreCase 忽略大小寫;非貪婪 *? 避免跨標籤匹配。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved