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

不懂,这个正则表达式
class Program
  {
  static void Main(string[] args)
  {
  string pattern = @"\d*";
  Regex rgx = new Regex(pattern);
  string sentence = "df97jk";
  foreach (Match match in rgx.Matches(sentence))
  {
  Console.WriteLine("{0}--{1}", match.Value, match.Index);
  }
  Console.ReadKey();
  }
  }
上面的正则表达式搜索连续的数字,最后的输出结果,怎么是这样的呢?
--0
--1
97--2
--4
--5
--6

不是只有97吗?其它怎么又输出了呢?
而下面这个例子
 class Program
  {
  static void Main(string[] args)
  {  
  string pattern = @"\b\w+es\b";
  Regex rgx = new Regex(pattern);
  string sentence = "Who writes these notes?";
  foreach (Match match in rgx.Matches(sentence))
  {
  Console.WriteLine("{0}--{1}", match.Value, match.Index);
  }
  Console.ReadKey();
  }
  }
搜索以es结尾的,最后的输出结果是:
writes--4
notes--17

其它不匹配的,为什么又没用输出来呢?


两个例子,为什么输出结果不同呢?

------解决方案--------------------
这个问题我恰巧知道一点,请参考:
\d* 能匹配abx……z,也就是说任意的匹配都会true,如果是数字则结果是数字,如果非数字则结果为""

第二例中@"\b\w+es\b"不能匹配其他单词。
------解决方案--------------------
主要是第一例中的"*"迷惑了结果,如果 是\d+则情况便不一样。
------解决方案--------------------
* 是匹配0次或任意多次,可以一次都不匹配,也就是说匹配空,一个位置而已
+ 是匹配1次或任意多次,至少要匹配一次

*的例子中,除了97,其它匹配的都仅仅是个位置而已

比如我们限制输入为数字
//可以为空
^\d*$
//不可以为空
^\d+$

参考
正则基础之——NFA引擎匹配原理

------解决方案--------------------
*匹配前面的\d任意次,所以即使不是数字也会被选出,如果要选出连续数字,对于你的"df97jk"可以用
(@"\d+");