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