用 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