编辑
2025-09-24
C#
00

目录

Match 方法
Matches 方法

在C#中,Regex 类提供了多种方法来进行正则表达式的匹配操作,包括 Match 方法和 Matches 方法。通过这些方法,我们可以对输入字符串进行灵活的匹配和处理。

Match 方法

C#
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "Hello, world! This is a test."; string pattern = @"\b\w{5}\b"; // 匹配5个字母的单词 Regex regex = new Regex(pattern); Match match = regex.Match(input); if (match.Success) { Console.WriteLine(match.Value); // 输出:Hello } } }

image.png

在上面的例子中,我们使用了 Match 方法来查找输入字符串中第一个匹配正则表达式的子串。这种匹配方式适用于需要从文本中提取特定模式的信息,比如提取邮件地址、电话号码等。

Matches 方法

C#
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "The cat and the dog are good friends."; string pattern = @"\b\w{3}\b"; // 匹配3个字母的单词 Regex regex = new Regex(pattern); MatchCollection matches = regex.Matches(input); foreach (Match match in matches) { Console.WriteLine(match.Value); // 输出:The cat and the dog are } } }

image.png

在这个例子中,我们使用了 Matches 方法来查找输入字符串中所有匹配正则表达式的子串。这种匹配方式适用于需要统计文本中特定模式出现的次数,或者对所有匹配的内容进行批量处理的情况。

通过以上例子,我们可以看到在C#中使用 Match 方法和 Matches 方法可以非常灵活地对输入字符串进行正则表达式的匹配操作,从而实现各种复杂的文本处理需求。这些方法在处理文本解析、数据提取、格式验证等场景中都有广泛的应用。希望以上例子可以帮助你更好地理解和应用正则表达式的匹配操作。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!