插件窝 干货文章 C# Regex.MatchCollection使用教程 - 获取字符串中所有匹配项

C# Regex.MatchCollection使用教程 - 获取字符串中所有匹配项

C#中使用Regex.MatchCollection获取所有正则匹配项

在C#开发中,正则表达式是处理字符串的强大工具。Regex.MatchCollection类可以帮助我们获取字符串中所有符合正则表达式模式的匹配项。本文将详细介绍如何使用这个功能。

Regex.MatchCollection基本用法

Regex.MatchCollection是System.Text.RegularExpressions命名空间中的一个类,它表示通过正则表达式匹配操作找到的成功匹配的集合。

using System.Text.RegularExpressions;

string input = "abc123def456ghi789";
string pattern = @"\d+"; // 匹配一个或多个数字

MatchCollection matches = Regex.Matches(input, pattern);

foreach (Match match in matches)
{
    Console.WriteLine(match.Value);
}

实际应用示例

1. 提取所有电子邮件地址

string text = "联系我:test1@example.com 或 test2@domain.com";
string emailPattern = @"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b";

MatchCollection emailMatches = Regex.Matches(text, emailPattern);

foreach (Match match in emailMatches)
{
    Console.WriteLine("找到邮箱:" + match.Value);
}

2. 获取HTML中的所有链接

string html = "链接1链接2";
string urlPattern = "href=['\"]([^'\"]*)['\"]";

MatchCollection urlMatches = Regex.Matches(html, urlPattern);

foreach (Match match in urlMatches)
{
    Console.WriteLine("找到URL:" + match.Groups[1].Value);
}

性能优化建议

  1. 对于频繁使用的正则表达式,考虑使用RegexOptions.Compiled选项预编译
  2. 避免在循环中重复创建Regex对象
  3. 使用非贪婪匹配(.*?)代替贪婪匹配(.*)提高效率
  4. 考虑使用Regex.Match而不是Matches当只需要第一个匹配时

常见问题解答

Q: MatchCollection和Match[]数组有什么区别?

A: MatchCollection是一个延迟求值的集合,只有在访问时才会计算匹配项,而Match[]数组会立即计算所有匹配项。

Q: 如何获取匹配项的位置信息?

A: 每个Match对象包含Index(匹配开始位置)和Length(匹配长度)属性。

Q: 为什么我的正则表达式匹配不到任何结果?

A: 请检查正则表达式是否正确,可以使用在线正则表达式测试工具验证。