C# 中的 Regex 類及其類方法是什麼?
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 建構函式中指定的正則表示式模式定義的位置,將輸入字串拆分為子字串陣列。 |
以下示例使用 Matches() 方法搜尋指定的輸入字串:
示例
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
廣告