用 Regex 在 C# 中進行模式匹配
正則表示式是一種可以與輸入文字進行匹配的模式。模式由一個或多個字元字面值、運算子或結構組成。
讓我們看一個使用 Regex 顯示以字母“M”開頭的單詞的示例。
示例
using System;
using System.Text.RegularExpressions;
namespace Demo {
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 = "Mandatory requirements for a Cricket Match Event!";
Console.WriteLine("Matching words that start with 'M': ");
showMatch(str, @"\bM\S*");
Console.ReadKey();
}
}
}輸出
Matching words that start with 'M': The Expression: \bM\S* Mandatory Match
上面是我的字串。
string str = "Mandatory requirements for a Cricket Match Event!";
為了獲得所有以“M”開頭的單詞,我使用了以下模式 -
@"\bM\S*
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP