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])"+@"(?<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();

        }
    }
}

“查询列表”文件:

来自 212.77.100.101 www.wp.pl 的回复时间:21:37
111.41.130.55 www.cnn.com 回复时间:05:33
230.77.100.101 www.piting.com 回复时间:04:12
65.77.100.101 www.ha.org 回复时间:12:55
来自 200.77.100.101 www.example.com 的回复时间:07:56

该程序编译并运行,但空的控制台窗口一直打开。为什么?

4

1 回答 1

3

因为没有任何东西与正则表达式匹配

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

您只需连接 2 个字符串,复合正则表达式期望字符串ip后面time没有任何其他内容(甚至是空格)。

您需要将其更改为

@"(?<ip>([0-9]+\.){3}[0-9]).*(?<time>(\s[0-2][0-9]:[0-9][0-9]))"
                           ^------- "anything" between first and second group
于 2012-06-09T22:47:07.163 回答