gpt4 book ai didi

.net - 正则表达式在下一行不以给定字符串开头时删除换行符

转载 作者:行者123 更新时间:2023-12-05 03:06:31 25 4
gpt4 key购买 nike

在 .net 中工作,我正在解析一个日志文件,其中有些行不以“2018”开头。我需要一个 .Match 子句,它会找到该行以字符串“2018 以外的任何内容开头的行(请注意包括双引号)。找到后(这是棘手的一点)- 从违规行 之前的行中删除换行符。换句话说,将违规行附加到它上面的行。

"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 之间的限定符。所有变体都没有改变输出。

最佳答案

您的代码可能存在的问题按自上而下的顺序排列

1- 我看到了 File.ReadAllText() 的文档页面 emphasizes :

The resulting string does not contain the terminating carriage return and/or line feed.

如果这是问题所在,请查看 this thread ,我不是 .NET 专家。

2- 你需要 @-quote caring about inner double quotation mark 旁边的正则表达式字符串("" 表示 @ 引号字符串中的 ")并删除 s 标志,这是额外的。

Regex rx = new Regex(@"(?m)\r?\n^(?!""2018)");

3- 接下来是您提供的替换字符串。你应该什么都不替换。 Zero-Width Negative Lookahead Assertion断言但不消费:

str = rx.Replace(str, ""); 

Live demo

关于.net - 正则表达式在下一行不以给定字符串开头时删除换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49225638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com