我有以下日志行格式,粗体部分在行之间变化,其余部分是模式(当然行号和时间也在变化但不相关)。
Line 1732:2014-10-12 09:21:26,672 DEBUG [Default_Thread_7] file.name.path.location - [TestStrinn Sys / 1 ] 来自Gateway的
我希望能够从这种确切格式的行中检索" Sys " ,数字" 1 " " SpecificNotification "这是从一行到另一行改变变量。
答案 0 :(得分:3)
您可以将Regex.Matches
与以下正则表达式一起使用:
(\w+)\/(\d+)\]\s+(\w+)
代码:
string input = @"Line 1732: 2014-10-12 09:21:26,672 DEBUG [Default_Thread_7] file.name.path.location - [TestStrinn Sys/1] SpecificNotification message arrived from Gateway";
Regex rgx = new Regex(@"(\w+)\/(\d+)\]\s+(\w+)");
foreach (Match m in rgx.Matches(input)) {
Console.WriteLine(m.Groups[1].Value);
Console.WriteLine(m.Groups[2].Value);
Console.WriteLine(m.Groups[3].Value);
}
答案 1 :(得分:2)
使用capturing groups捕获所需的字符。稍后您可以通过back-referencing引用捕获的字符。
String input = @"Line 1732: 2014-10-12 09:21:26,672 DEBUG [Default_Thread_7] file.name.path.location - [TestStrinn Sys/1] SpecificNotification message arrived from Gateway";
Regex rgx = new Regex(@"^\s*Line\s*\d+:\s*.*?\s*file\.name\.path\.location\s*-\s*\[\s*\S+\s*([^\/]*)\/(\d+)\]\s*(\S+)");
foreach (Match m in rgx.Matches(input))
{
Console.WriteLine(m.Groups[1].Value);
Console.WriteLine(m.Groups[2].Value);
Console.WriteLine(m.Groups[3].Value);
}
<强>输出:强>
Sys
1
SpecificNotification