c# - 将 Notepad++ REGEX 转换为 .NET C#

标签 c# .net regex

使用竖线分隔的文件。目前,我使用 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/

相关文章:

c# - 将压缩图像与原始图像进行比较

c++ - 使用 Python 删除 C 和 C++ 注释?

REGEX_MATCH 匹配 PG 而不是 PG13,反之亦然

c# - 带有 Web 引用的 OperationContextScope

c# - 在负载均衡器后面运行的 Identity Server 4

c# - 如何在 C# 中更改 NaN 字符串表示形式?

javascript - 如何制作验证电话号码中的国家/地区代码的正则表达式

c# - 如何从 Visual studio 2017 预览版 2 指定 Azure Function 的输出绑定(bind)?

c# - ASP.NET 中的 Gridview 删除按钮

c# - Websphere MQ & .NET - WriteString() 属性使消息太长