在正则表达式搜索中只查找第一个匹配项

本文关键字:第一个 查找 正则表达式 搜索 | 更新日期: 2023-09-27 17:49:18

Regex messageServerRegex = 
    new Regex(@"([0-9'-]{10})' ([0-9:]{8})' '[TEXT']' ('[Server'])' ([^'[]*)");
if (messageServerRegex.IsMatch(rchConsoleText))
{
    var infoMatches = messageServerRegex.Split(rchConsoleText);
    Console.WriteLine("Date: {0}'nTime: {1}'nType: {2}'nMessage: {3}",
    infoMatches[1], infoMatches[2], infoMatches[3], infoMatches[4]);
}

下面是我们希望服务器过滤的两个文本示例

2012-12-24 02:24:18 [TEXT] [Server] 2012-12-24 02:24:18 [TEXT] [Server]示例文本。

我们想从这行返回的结果是:

<>之前日期:2012-12-14时间:02:24:18类型:[TEXT] [Server]消息:2012-12-24 02:24:18 [TEXT] [Server]示例文本。之前

但是它会返回:

<>之前日期:2012-12-14时间:02:24:18类型:[TEXT] [Server]消息:2012-12-24 02:24:18之前

你可以看到,它只显示日期和时间,这是因为正则表达式过滤器,所以我怎么让它只削减日期和时间1次?

第二个例子很好,它是:

2012-12-24 02:24:18 [TEXT] [Server]示例文本示例文本示例文本。

我们想从这行返回的结果是:

<>之前日期:2012-12-14时间:02:24:18类型:[TEXT] [Server]信息:示例文本示例文本示例文本。

在正则表达式搜索中只查找第一个匹配项

我不知道你的输入是否被分割成行。如果是这样的话,很容易使用Match。

     var inputs = new string[]{
        @"2012-12-24 02:24:18 [TEXT] [Server] 2012-12-24 02:24:18 [TEXT] [Server] Sample text.",
        @"2012-12-24 02:24:18 [TEXT] [Server] Sample text sample text sample text."};
     foreach(string input in inputs)
     {
        string pattern = @"([0-9'-]{10}) ([0-9:]{8}) '[TEXT']' ('[Server']) (.*)";
        var match = Regex.Match(input, pattern);
        Console.WriteLine(
           "Date: {0}'nTime: {1}'nType: {2}'nMessage: {3}",
           match.Groups[1].Value, match.Groups[2].Value, match.Groups[3].Value, match.Groups[4].Value);
     }

如果不是,它会变得更困难-而不是.*,它将是((?!something that indicates the next entry).)

regex中的最后一组不包括'['字符,如果它包含[字符,则会导致该行的文本部分不匹配。如果输入表示单个日志消息,则排除似乎没有必要。试试不使用。*,看看是否可以

如何:

^([0-9'-]{10})' ([0-9:]{8})'s*'[TEXT']'s*'[Server']'s*(.*)