
- C# 基礎教程
- C# - 首頁
- C# - 概述
- C# - 環境
- C# - 程式結構
- C# - 基本語法
- C# - 資料型別
- C# - 型別轉換
- C# - 變數
- C# - 常量
- C# - 運算子
- C# - 決策
- C# - 迴圈
- C# - 封裝
- C# - 方法
- C# - 可空型別
- C# - 陣列
- C# - 字串
- C# - 結構體
- C# - 列舉
- C# - 類
- C# - 繼承
- C# - 多型
- C# - 運算子過載
- C# - 介面
- C# - 名稱空間
- C# - 預處理器指令
- C# - 正則表示式
- C# - 異常處理
- C# - 檔案I/O
C# - 正則表示式
正則表示式是一種可以與輸入文字匹配的模式。.Net 框架提供了一個正則表示式引擎,允許進行這種匹配。模式由一個或多個字元字面量、運算子或構造組成。
定義正則表示式的構造
有各種型別的字元、運算子和構造可以讓你定義正則表示式。點選以下連結查詢這些構造。
Regex 類
Regex 類用於表示正則表示式。它具有以下常用方法:
序號 | 方法和描述 |
---|---|
1 | public bool IsMatch(string input) 指示在 Regex 建構函式中指定的正則表示式是否在指定的輸入字串中找到匹配項。 |
2 | public bool IsMatch(string input, int startat) 指示在 Regex 建構函式中指定的正則表示式是否在指定的輸入字串中找到匹配項,從字串中的指定起始位置開始。 |
3 | public static bool IsMatch(string input, string pattern) 指示指定的正則表示式是否在指定的輸入字串中找到匹配項。 |
4 | public MatchCollection Matches(string input) 搜尋指定的輸入字串中正則表示式的所有出現。 |
5 | public string Replace(string input, string replacement) 在指定的輸入字串中,將與正則表示式模式匹配的所有字串替換為指定的替換字串。 |
6 | public string[] Split(string input) 根據 Regex 建構函式中指定的正則表示式模式定義的位置,將輸入字串拆分為子字串陣列。 |
有關方法和屬性的完整列表,請閱讀 Microsoft 的 C# 文件。
示例 1
以下示例匹配以“S”開頭的單詞:
using System; using System.Text.RegularExpressions; namespace RegExApplication { class Program { private static void showMatch(string text, string expr) { Console.WriteLine("The Expression: " + expr); MatchCollection mc = Regex.Matches(text, expr); foreach (Match m in mc) { Console.WriteLine(m); } } static void Main(string[] args) { string str = "A Thousand Splendid Suns"; Console.WriteLine("Matching words that start with 'S': "); showMatch(str, @"\bS\S*"); Console.ReadKey(); } } }
編譯並執行上述程式碼後,將產生以下結果:
Matching words that start with 'S': The Expression: \bS\S* Splendid Suns
示例 2
以下示例匹配以“m”開頭並以“e”結尾的單詞:
using System; using System.Text.RegularExpressions; namespace RegExApplication { class Program { private static void showMatch(string text, string expr) { Console.WriteLine("The Expression: " + expr); MatchCollection mc = Regex.Matches(text, expr); foreach (Match m in mc) { Console.WriteLine(m); } } static void Main(string[] args) { string str = "make maze and manage to measure it"; Console.WriteLine("Matching words start with 'm' and ends with 'e':"); showMatch(str, @"\bm\S*e\b"); Console.ReadKey(); } } }
編譯並執行上述程式碼後,將產生以下結果:
Matching words start with 'm' and ends with 'e': The Expression: \bm\S*e\b make maze manage measure
示例 3
此示例替換多餘的空格:
using System; using System.Text.RegularExpressions; namespace RegExApplication { class Program { static void Main(string[] args) { string input = "Hello World "; string pattern = "\\s+"; string replacement = " "; Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement); Console.WriteLine("Original String: {0}", input); Console.WriteLine("Replacement String: {0}", result); Console.ReadKey(); } } }
編譯並執行上述程式碼後,將產生以下結果:
Original String: Hello World Replacement String: Hello World