使用竖线分隔的文件。目前,我使用 Notepad++ 查找并替换 REGEX 模式 ^(?:[^|]*\|){5}\K[^|]*
将第 5 行之间的所有行替换为空字符串和第 6 个 |
。我正在尝试以编程方式执行此过程,但 .NET 不支持 \K
。我已经尝试了几个向后查找的实例,但我似乎无法理解它。
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
string line2 = null;
string finalLine = line;
string[] col = line.Split('|');
if (col[5] != null)
{
line2 = Regex.Replace(line, @"^(?:[^|]*\|){5}\K[^|]*", "");
最佳答案
\K
是不支持锚定 look-behind assertions 的正则表达式语法/引擎的“解决方法” .
.NET 的正则表达式语法 has look-behind assertions (使用语法 (?<=subexpression)
),所以使用它们:
Regex.Replace(line, @"(?<=^(?:[^|]*\|){5})[^|]*", "")
在 .NET 的上下文中,此模式现在描述:
(?<= # begin (positive) look-behind assertion
^ # match start of string
(?: # begin non-capturing group
[^|]*\| # match (optional) field value + delimiter
){5} # end of group, repeat 5 times
) # end of look-behind assertion
[^|]* # match any non-delimiters (will only occur where the lookbehind is satisfied)
关于c# - 将 Notepad++ REGEX 转换为 .NET C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66497484/