首页 > 解决方案 > 为什么它不打印 C# 中的最后一个正则表达式组

问题描述

我写了这个非常直接的正则表达式代码

using System;
using System.Text.RegularExpressions;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {

            string lines = "2019-05-07 11:50:28, INFO Ayush Singhania, Level 1, EID: 1001, UID: ayush.power, Message: Create a Job";
            Regex pattern = new Regex(@"(?<Date>.*?\s)(?<Time>.*?), INFO(?<Name>.*?),(?<Level>.*?), EID: (?<EID>.*?), UID: (?<UID>.*?), Message: (?<Message>.*?)");

            MatchCollection myMatchCollection = pattern.Matches(lines);
            foreach (Match myMatch in myMatchCollection)
            {
                var Date = myMatch.Groups["Date"].Value;
                var Time = myMatch.Groups["Time"].Value;
                var Name = myMatch.Groups["Name"].Value;
                var Level = myMatch.Groups["Level"].Value;
                var EID = myMatch.Groups["EID"].Value;
                var UID = myMatch.Groups["UID"].Value;
                var Message = myMatch.Groups["Message"].Value;

                Console.Out.WriteLine(Date);
                Console.Out.WriteLine(Time);
                Console.Out.WriteLine(Name);
                Console.Out.WriteLine(Level);
                Console.Out.WriteLine(EID);
                Console.Out.WriteLine(UID);
                Console.Out.WriteLine(Message);
            }
        }
    }
}

以下的输出是:

2019-05-07
11:50:28
Ayush Singhania
1 级
1001
ayush.power
......(最后一行为空白)

最后一组的一切都很好 - “消息”
它不打印任何东西。谁能建议为什么会这样?
我也认为我的正则表达式模式是正确的。在这里查看https://regex101.com/r/ysawNT/1

标签: c#regex

解决方案


除了使用Groups["Message"]应该是的错误消息外MSG,最后一部分是空的,因为最后一部分没有设置边界,并且非贪婪.*?也满足不匹配任何内容。

你可以做的是匹配字符串的其余部分使用(?<MSG>.*)

正则表达式演示| C# 演示

在此处输入图像描述


推荐阅读