使用正则表达式 regex.matches 方法可以提取文本中所有符合规则的片段。调用该方法并传入模式字符串,它会返回一个包含所有匹配项的集合,通过遍历该集合即可获取每个匹配的文本内容。

Regex.Matches 如何返回匹配结果集
Regex.Matches 方法直接返回一个 MatchCollection 对象,其中包含了所有非重叠的匹配项。开发者可以通过索引访问或迭代器遍历这个集合,从而逐个处理提取出的片段。

using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string text = "Order ID: 12345, Price: $99.99, Status: Active";
string pattern = @"\d+";
MatchCollection matches = Regex.Matches(text, pattern);
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
}
}
如何处理匹配中的捕获组数据
当正则表达式包含捕获组时,每个 Match 对象的 Groups 属性会存储这些分组的数据。通过访问 Groups[1]、Groups[2] 等索引,可以提取出规则中特定部分的子串,而不仅仅是整个匹配项。

using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string text = "Name: Alice, Age: 30";
string pattern = @"Name: (?<name>\w+), Age: (?<age>\d+)";
Match match = Regex.Match(text, pattern);
if (match.Success)
{
Console.WriteLine($"Name: {match.Groups["name"].Value}, Age: {match.Groups["age"].Value}");
}
}
}
基于输入文本中连续数字的提取行为验证
在输入文本包含连续数字序列时,Regex.Matches 会将每一段连续的数字视为一个独立的匹配项。例如,在字符串 "123 456" 中,它会提取出 "123" 和 "456" 两个独立的匹配,而不是将它们合并为一个整体,这取决于正则表达式是否包含空格匹配逻辑。


















