使用Regex在C#中进行模式匹配
正则表达式是可以与输入文本匹配的模式。模式由一个或多个字符文字,运算符或构造组成。
让我们看一个使用正则表达式显示以字母“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 = "板球比赛的强制性要求!";
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 = "板球比赛的强制性要求!";
为了获得所有以'M'开头的单词,我使用了以下模式-
@"\bM\S*
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短