日期:2014-05-18  浏览次数:20517 次

正则表达式语法问题
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而是两个换行?



------解决方案--------------------
你的正则是(?!3),它只匹配位置,不匹配任何东西,查看一下你上面的代理中Match对象的Index属性,你就会明白我说的。或者把正则改为

(?!3)\d

参考我的博客贴子
http://blog.joycode.com/saucer/archive/2006/10/11/84963.aspx

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


------解决方案--------------------
又见楼主,呵呵:)

^ 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)这个条件,所以匹配失败