我有以下日志行格式,粗体部分正在逐行更改,其余部分是模式(当然行号和时间也在变化但不相关) 。如何使用正则表达式从字符串中检索信息
线1732:2014年10月12日09:21:26672 DEBUG [Default_Thread_7] file.name.path.location - [TestStrinn Sys系统/] SpecificNotification消息从网关
到达我希望能够从这种确切格式的行中检索“Sys”,数字“”和“特定通知”,它们正在逐行改变变量。
我有以下日志行格式,粗体部分正在逐行更改,其余部分是模式(当然行号和时间也在变化但不相关) 。如何使用正则表达式从字符串中检索信息
线1732:2014年10月12日09:21:26672 DEBUG [Default_Thread_7] file.name.path.location - [TestStrinn Sys系统/] SpecificNotification消息从网关
到达我希望能够从这种确切格式的行中检索“Sys”,数字“”和“特定通知”,它们正在逐行改变变量。
您可以使用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);
}
@Unihedron微优化! – 2014-10-12 10:03:45
谢谢,我该如何添加分组?为了从变量中检索信息? – user2878881 2014-10-12 10:13:06
@ user2878881检查出现在 – 2014-10-12 10:14:45
使用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
显示你的努力 – 2014-10-12 09:47:47