#region 匹配时设置 显示捕获 选项
/// <summary>
/// 匹配时设置 显示捕获 选项
/// </summary>
protected void test16()
{
string pattern = @"(\d{3})";
string str = "123a432";
//匹配时设置为“ExplicitCapture”,将不捕获没有显式命名的组
Regex reg = new Regex(pattern, RegexOptions.ExplicitCapture);
if (reg.IsMatch(str))
{
Match match = reg.Match(str);
GroupCollection coll = match.Groups;
int i = 0;
foreach (Group item in coll)
{
Console.WriteLine("group" + i + ": " +item.ToString());
//Console.WriteLine("group" + i + ": " + coll[i].Value.ToString());
i++;
}
}
}
#endregion
#region 获取捕获的多个内容后,循环输出
/// <summary>
/// 获取捕获的多个内容后,循环输出
/// </summary>
protected void test17()
{
string pattern = @"a.*?b";
string input = "aabaaaaaaaaaaab";
Regex regex = new Regex(pattern);
if (regex.IsMatch(input))
{
MatchCollection colls = Regex.Matches(input, pattern);
foreach (Match item in colls)
{
Console.WriteLine(item.Value.ToString());
}
}
}
#endregion
#region 获取捕获的多个分组后,循环输出
/// <summary>
/// 获取捕获的多个分组后,循环输出
/// </summary>
protected void test18()
{
string pattern = @"(\d{3})(\w{2})";
string input = "123ab";
Regex regex = new Regex(pattern);
if (regex.IsMatch(input))
{
GroupCollection colls = Regex.Match(input, pattern).Groups;
Console.WriteLine(Regex.Match(input, pattern).Value);
Console.WriteLine("---------------------");
foreach (Group item in colls)
{
Console.WriteLine(item.Value.ToString());
}
}
}
#endregion
C#程序中利用正则表达式对字符串分组并获取组值
本文转载:CSDN博客