我有一个带有repetitve结构的文本文件作为标题和详细记录,例如
StopService::
697::12::test::20::[email protected]::20 Main Rd::Alcatraz::CA::1200::Please send me Information to
[email protected]::0::::
我想删除标题和详细记录之间的换行符,以便将它们作为单个记录来处理,因为详细记录也可以包含换行符,所以我只需要删除直接跟随::
符号的换行符。
使用正则表达式时我不是专业人士,因此我搜索并尝试使用此方法,但它不起作用:
string text = File.ReadAllText(path);
Regex.Replace(text, @"(?<=(:))(?!\1):\n", String.Empty);
File.WriteAllText(path, text);
我也尝试过这个:
Regex.Replace(text, @"(?<=::)\n", String.Empty);
知道如何在这种情况下使用正则表达式吗?我的输出应如下所示:
StopService::697::12::test::20::[email protected]::20 Main Rd::Alcatraz::CA::1200::Please send me Information to
[email protected]::0::::
逐行读取文件。检查第一行,如果不等于StopService::
则不要Environment.Newline
在其后添加换行符()。
您可以::
使用后向匹配在第一个之后匹配换行符(?<=^[^:]*::)
:
var str = "StopService::\r\n697::12::test::20::[email protected]::20 Main Rd::Alcatraz::CA::1200::Please send me Information to\r\[email protected]::0::::";
var rgx = new Regex(@"(?<=^[^:]*::)[\r\n]+");
Console.WriteLine(rgx.Replace(str, string.Empty));
输出:
StopService::697::12::test::20::[email protected]::20 Main Rd::Alcatraz::CA::1200::Please send me Information to
[email protected]::0::::
后视((?<=...)
)符合:
^
-字符串开始 [^:]*
-0个或多个其他字符 :
::
-2个冒号该[\r\n]+
模式可确保我们匹配所有换行符,即使有多个也不止。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句