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