一个筛选器字符串中的两个正则表达式组

本文关键字:两个 正则表达式 一个 筛选 字符串 | 更新日期: 2023-09-27 18:36:37

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

此程序编译并运行,但空控制台窗口始终打开。为什么?

一个筛选器字符串中的两个正则表达式组

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

@"(?<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