2012-12-24 38 views
0
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日2时24分18秒[文字] [服务器] 2012-12-24 02:24:18 [TEXT] [服务器]示例文本。

我们要从这条线后面的结果是:

 
Date: 2012-12-14 
Time: 02:24:18 
Type: [TEXT] [Server] 
Message: 2012-12-24 02:24:18 [TEXT] [Server] Sample text. 

但将响应回:

 
Date: 2012-12-14 
Time: 02:24:18 
Type: [TEXT] [Server] 
Message: 2012-12-24 02:24:18 

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

第二个例子能正常工作,这是:

2012年12月24日2点24分18秒[TEXT] [服务器]试样文本样本的文本样本的文本。

我们要从这条线后面的结果是:

 
Date: 2012-12-14 
Time: 02:24:18 
Type: [TEXT] [Server] 
Message: Sample text sample text sample text. 
+0

有没有你正在使用拆分理由吗?我认为这会让它变得比需要的复杂。为什么不在命名组中使用'regex.Match'或'.Matches'? –

+0

@ agent-j这不是在相同的输出中解析吗? –

回答

2

我不能告诉你的输入是否分解成行。如果是这样,使用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).)

+0

这使我走上了正确的道路,这几乎是我想要的,谢谢! –

0

最后一组在你的正则表达式不包括“[”,这会导致该行的文本部分不匹配,如果它包含一个[字符字符。如果输入代表单个日志消息,则排除似乎并不需要。尝试它没有排除,。*,并看看是否有效

+0

然后我得到这个输出:“消息:2”:(。 –

+0

没有注意到你正在使用分割。尝试agent-js建议并使用.match并使用正则表达式中的捕获组 – Kyle

0

如何:

^([0-9\-]{10})\ ([0-9:]{8})\s*\[TEXT\]\s*\[Server\]\s*(.*) 
相关问题