2012-06-09 42 views
1
using System; 
using System.IO; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Text.RegularExpressions; 

namespace RegExCs 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string rawData; 
      Regex filter = new Regex(@"(?<ip>([0-9]+\.){3}[0-9])"[email protected]"(?<time>(\s[0-2][0-9]:[0-9][0-9]))"); 


      rawData=File.ReadAllText("Query list"); 

      MatchCollection theMatches = filter.Matches(rawData); 

      foreach (Match theMatch in theMatches) 
      { 
       Console.WriteLine("ip: {0}\n",theMatch.Groups["ip"]); 
       Console.WriteLine("time: {0}\n", theMatch.Groups["time"]); 
      } 


      Console.ReadKey(); 

     } 
    } 
} 

“查询列表”文件:两个正则表达式组

 
Reply from 212.77.100.101 www.wp.pl time: 21:37 
Reply from 111.41.130.55 www.cnn.com time: 05:33 
Reply from 230.77.100.101 www.piting.com time: 04:12 
Reply from 65.77.100.101 www.ha.org time: 12:55 
Reply from 200.77.100.101 www.example.com time: 07:56 

这个程序编译和运行,但开空控制台窗口的全部时间。为什么?

回答

3

因为没有相匹配的正则表达式

@"(?<ip>([0-9]+\.){3}[0-9])(?<time>(\s[0-2][0-9]:[0-9][0-9]))" 

你正好连接两个字符串,以及化合物的正则表达式预期的字符串,ip随后time他们之间没有任何东西(甚至是空格)。

您需要将其更改为

@"(?<ip>([0-9]+\.){3}[0-9]).*(?<time>(\s[0-2][0-9]:[0-9][0-9]))" 
          ^------- "anything" between first and second group