正则表达式匹配多个字符串

时间:2016-03-22 09:41:50

标签: c# regex

我想解析一个日志文件以检索timetypemessage。日志文件的构造如下:

[08:52:18] [ERROR] Ceci doit aparaitre 
[08:52:18] [WARN] Bonjour 

我目前正在这样做:

var result = Regex.Match(fileLogs, @"/\[(.+)\] \[(.+)\] (.+)/g");

哪个在RegexStorm等网站上正常运行,但在我的代码上却没有。我真的不明白为什么。

我想检索这些元素以创建Log的新实例(它只有3个属性:timetypemessage

1 个答案:

答案 0 :(得分:4)

删除最初的/和最终的/g。你是用C#编程的,而不是Javascript编程。

var result = Regex.Match(fileLogs, @"\[(.+)\] \[(.+)\] (.+)");

Ideone显示现在可以正常运行:here

要正确拆分,您可以使用以下内容:

var result = Regex.Matches(fileLogs, @"\[(.+)\] \[(.+)\] (.+)");

foreach (Match match in result)
{
    string time = match.Groups[1].Value;
    string type = match.Groups[2].Value;
    string messsage = match.Groups[3].Value;
    Console.WriteLine("{0} | {1} | {2}", time, type, messsage);
}

请注意使用Regex.Matches

Ideone:https://ideone.com/QkTYwS