Converting Notepad++ REGEX to .NET C#

Viewed 107

Working with a pipe-delimited file. Currently, I use Notepad++ find and replace REGEX pattern ^(?:[^|]*\|){5}\K[^|]* that replaces all lines with an empty string between the 5th and 6th |. I'm trying to programmatically do this process, but .NET does not support \K. I've tried a few instances of the backward lookup, but I cannot seem to grasp it.

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[^|]*", "");
2 Answers

\K is a "workaround" for regex grammars/engines that don't support anchoring against look-behind assertions.

.NET's regex grammar has look-behind assertions (using the syntax (?<=subexpression)), so use them:

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

In the context of .NET, this pattern now describes:

(?<=               # 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)

No need using lookbehinds, use capturing groups and backreferences:

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

See proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        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))
Related