【发布时间】:2018-03-11 22:06:03
【问题描述】:
在 .net 中工作,我正在解析一个日志文件,其中某些行不以“2018”开头。我需要一个 .Match 子句来查找该行以除字符串“2018”以外的任何内容开头的行(请注意包括双引号)。找到时(这是棘手的一点) - 从有问题的行 before 行中删除换行符。换句话说,将违规行附加到它上面的行。
"2018-02-22 10:06:10,857","[7]"," ERROR","MyApp.Web.Infrastructure.ErrorResponseCommand","ErrorResponseCMD logs Controller: webinar | Action: Index",""
"2018-02-22 10:06:37,742","[11]"," INFO ","MyApp.Web.MvcApplication","Anon Session Starts with: {""FirstPage"": ""https://www.bankwebinars.com/wp-login.php"", ""QueryString"": """", ""SessionId"": ""uhnev2dnds33dastwrdgftvm"", ""FirstCookies"": {""CookieName"": ""ASP.NET_SessionId"", ""Value"": ""uhnev2dnds33dastwrdgftvm""}}",""
"2018-02-22 10:06:48,053","[11]"," INFO ","MyApp.Web.Controllers.CartController","SessionInfo{
""FirstPage"": null,
""RemoteAddress"": ""207.46.13.159"",
""RemoteHost"": ""207.46.13.159"",
""RemoteUser"": """",
RelativeConfirmPasswordResetUrl:Account/PasswordResetConfirm
//and other non-predictable BOL patterns.
},""
"2018-02-22 10:06:10,857","[7]"," ERROR","MyApp.Web.Infrastructure.ErrorResponseCommand","ErrorResponseCMD logs Controller: webinar | Action: Index",""
附录:尝试了建议的模式 - 并注意到该模式适用于 regex101 的沙箱 - 肯定还有其他问题。这是我当前的代码。
string str = File.ReadAllText("myLog.log");
Regex rx = new Regex("(?m)\r?\n^(?!\"2018)", RegexOptions.Singleline);
str = rx.Replace(str, "\"2018");
File.WriteAllText("test1.txt", str);
我已经尝试了一系列的模式变化 - 例如我认为 RegexOption 子句等同于 (?m) 短语,所以我尝试省略它。单行应该是我想要的,因为它将整个文件视为单行,但我也尝试过多行模式。这是一个 Windows 文件,所以 ?不需要 \r 和 \n 之间的限定符。没有任何变体改变了输出。
【问题讨论】:
-
你的模式有什么问题?
-
或者更好,你尝试过的模式是什么?