string s="6";
Regex r=new Regex(@"(?!3)");
Console.WriteLine(r.IsMatch(s));
Match m=r.Match(s);
Console.WriteLine(r.Matches(s,0).Count);
while(m.Success )
    {
          Console.WriteLine(m);
           m=m.NextMatch();
    }结果为:
2
True,然后是两个换行。程序结果不能理解,结果表明有2个符合要求的匹配,但为什么匹配的输出结果没有字符6而是两个换行?

解决方案 »

  1.   

    你的正则是(?!3),它只匹配位置,不匹配任何东西,查看一下你上面的代理中Match对象的Index属性,你就会明白我说的。或者把正则改为(?!3)\d参考我的博客贴子
    http://blog.joycode.com/saucer/archive/2006/10/11/84963.aspx
      

  2.   

    (?!3) 是原子零宽度断言,举个例子,a(?!3),这个模式是说要与后面不带3的a匹配,
    a2  与这个串中的a匹配,
    a3  不匹配
    a4  匹配
      

  3.   

    谢谢saucer(思归)和photoplan()
    对于"(?!3),它只匹配位置,不匹配任何东西" 我想能不能这样理解:上个程序的结果表明有2个匹配,它匹配输入字符串"6"的开始位置(^)和结束位置($).所以输出匹配的值是两个"空"值.
    但是看下面的程序:
    string s="6"; 
    Regex r=new Regex(@"^(?!3)$");
            Console.WriteLine("Matches:"+r.Matches(s,0).Count);
            Console.WriteLine(r.IsMatch(s));
            Match m=r.Match(s);
            while(m.Success )
            {
            Console.WriteLine("Index:{0},Vlaue:{1}",m.Index,m);
            m=m.NextMatch();
            }
    程序输出结果为:Matches:0
                   False
    一个匹配也没有.我先前以为它是会匹配输入字符串"6"的(开始边界、字符6、结束边界)把程序改一下:r=new Regex(@"^(?!3)");
    程序输出结果为:Matches:1
               True
               Index:0,Value:空
    这个结果我先前认为它是会匹配的,并且输出的value不是空,而是"6"(开始边界、字符6)再把程序改一下:r=new Regex(@"^(6)");
    程序输出结果为:Matches:1
               True
               Index:0,Value:6
    这个结果与我预想的是一致的.前面两个正则表达式"^(?!3)$"和@"^(?!3)"所产生的结果能不能解释一下,为什么不是我认为那样的?谢谢~~~~~
      

  4.   

    又见楼主,呵呵:)^ Specifies that the match must occur at the beginning of the string or the beginning of the line. 
    $ Specifies that the match must occur at the end of the string, before \n at the end of the string, or at the end of the line. 
    (?! subexpression) Zero-width negative lookahead assertion.
      
    以上三个都是Zero-width,即零宽度的,它们本身并不匹配任何字符,只是作为附加条件存在的^(?!3)$
    ^(?!3)
    这两个正则,从本身来看,它们都是零宽度的,所以无论是否匹配成功,都不会匹配任何内容第一个匹配失败是为是^$要求从开始位置一直匹配到结束位置,它要求中间不可以有任何字符,,即匹配成功的情况只能是空字符串,所以这里的(?!3)是多余的
    第二个能匹配成功,是因为它去掉了$这个限制,所以结果是匹配了开始位置,如果把测试字符串换成
    string s="3";
    因为不满足(?!3)这个条件,所以匹配失败