【问题标题】:Converting Notepad++ REGEX to .NET C#将 Notepad++ 正则表达式转换为 .NET C#
【发布时间】:2021-03-05 18:06:46
【问题描述】:

使用竖线分隔的文件。目前,我使用 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[^|]*", "");

【问题讨论】:

标签: c# .net regex


【解决方案1】:

\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)

【讨论】:

  • 我还想(向 OP)指出 .NET 的正则表达式引擎不仅支持 Lookbehinds,而且还支持非固定宽度 Lookbehinds(大多数其他正则表达式引擎不支持)。这就是为什么该模式在 Notepad++ 中不起作用(尽管它支持 Lookbehinds)。
【解决方案2】:

无需使用lookbehinds,使用捕获组和反向引用:

line2 = Regex.Replace(line, @"^((?:[^|]*\|){5})[^|]*", "$1");

proof

解释

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    (?:                      group, but do not capture (5 times):
--------------------------------------------------------------------------------
      [^|]*                    any character except: '|' (0 or more
                               times (matching the most amount
                               possible))
--------------------------------------------------------------------------------
      \|                       '|'
--------------------------------------------------------------------------------
    ){5}                     end of grouping
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  [^|]*                    any character except: '|' (0 or more times
                           (matching the most amount possible))

【讨论】:

    猜你喜欢
    • 2011-10-02
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多