在C#开发中,正则表达式是处理字符串的强大工具。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);
}
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);
}
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);
}
Q: MatchCollection和Match[]数组有什么区别?
A: MatchCollection是一个延迟求值的集合,只有在访问时才会计算匹配项,而Match[]数组会立即计算所有匹配项。
Q: 如何获取匹配项的位置信息?
A: 每个Match对象包含Index(匹配开始位置)和Length(匹配长度)属性。
Q: 为什么我的正则表达式匹配不到任何结果?
A: 请检查正则表达式是否正确,可以使用在线正则表达式测试工具验证。