用正则,我想匹配 5位数字里,有两个8的一组
如:87837,12345,45678,
取:87837(只两个8)
只两个是8的,5位数。。

解决方案 »

  1.   


     string numstr = "87837,12345,45678,68844";
                MatchCollection mc = Regex.Matches(numstr, @"\d{5}");
                foreach (Match mcnum in mc)
                {
                    string num = mcnum.Value;
                    if (num.ToCharArray().Where(x => x.ToString() == "8").Count() == 2)
                    {
                        Console.WriteLine(mcnum.Value);
                    }
                }
      

  2.   

    判断5个数字直接判断字符串长度,判断2个8用这个正则“\d*8\d*8\d*”,这两个必须分开判断。
      

  3.   

     string str = "87837,12345,45678";
                var result = Regex.Matches(str, @"(?(\d{5}(?=,|$))\d*?(8)[^\1]*?\1[^\1,]*)").OfType<Match>().Where(a=>!string.IsNullOrEmpty(a.Value)).Select(a=>a.Value);
      

  4.   

    void Main()
    {
    int[] ary=new int[]{87837,12345,45678,112481824};
    Regex reg=new Regex(@"^(?!([0-7]|9)+$)^(?!8+$)(?!([0-7]|9)*8([0-7]|9)*$)(?!([0-7]|9)*8([0-7]|9)*8([0-7]|9)*8([0-7]|9)*$)(?!([0-7]|9)*8([0-7]|9)*8([0-7]|9)*8([0-7]|9)*8([0-7]|9)*$)\d{5}$");
    foreach(int i in ary)
    Console.WriteLine("{0} --- {1}",i,reg.IsMatch(i.ToString()));
    /*
    87837 --- True
    12345 --- False
    45678 --- False
    112481824 --- False
    */
    }
      

  5.   

    void Main()
    {
     string str="87837,12345,45678,114818";
     Regex reg=new Regex(@"^(?!([0-7]|9)+$)^(?!8+$)(?!([0-7]|9)*8([0-7]|9)*$)(?!(([0-7]|9)*8){3}([0-7]|9)*$)(?!(([0-7]|9)*8){4}([0-7]|9)*$)\d{5}$");
     foreach(string s in str.Split(','))
    Console.WriteLine("{0} --- {1}",s,reg.IsMatch(s));
    }