同正则表达式捕获组的能实现不同个数吗?            string x = "abaaabb";
            Regex r1 = new Regex(@"(?<a>a)|(?<b>b)");
            foreach (Match m in r1.Matches(x))
            {
                Console.WriteLine("a = {0}",m.Groups["a"].Value);
                
            }
            foreach (Match m in r1.Matches(x))
            {
                
                Console.WriteLine("b = {0}", m.Groups["b"].Value);
            }
            Console.ReadLine();上面的代码,是相同个数,竟然出现了很多个空值来补成相同个数,不知道为什么????

解决方案 »

  1.   

    "(?<a>a)|(?<b>b)"
    你这样写结果捕获的个数肯定相同啊,因为字符串不是a就是b,也就是都是满足上面的正则的
    结果捕获的个数就是字符串的长度了
      

  2.   

    个数不是用Groups["b"].Value来表示的
      

  3.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {            string test = "1234abcdefg";
                Regex reg = new Regex(@"(?<num>[0-9])+(?<ch>[a-z])+");
                Match m = reg.Match(test);
                StringBuilder sb;
                if (m.Success)
                {                Console.WriteLine("result:" + m.Value + "\n");                Console.WriteLine("Group:" + m.Groups["num"].Value + "\n--------------\n");                foreach (Capture c in m.Groups["num"].Captures)
                    {                    Console.WriteLine("Capture:" + c + "\n");                }
                    Console.WriteLine("Group:" + m.Groups["ch"].Value + "\n--------------\n");                foreach (Capture c in m.Groups["ch"].Captures)
                    {                    Console.WriteLine("Capture:" + c + "\n");                }            }
            }    }
    }
      

  4.   


    没有实际需求,这种探讨我认为是没什么意义的这是跟语言相关的,在其它语言中,比如记得TCL中引用未参与匹配的捕获组,是会抛异常的
    而在,.NET中,没有匹配到,或是没有参与匹配的捕获组,如果去引用它的话,会直接返回一个空字符串
    甚至于你去引用一个根本就不存在的捕获组,也是一样的
    string x = "abaaabb";
    Regex r1 = new Regex(@"(?<a>a)|(?<b>b)");
    foreach (Match m in r1.Matches(x))
    {
        richTextBox2.Text += string.Format("c = {0}", m.Groups["c"].Value) + "\n";
    }