In general, \K
operator (that discards all text matched so far from the match memory buffer) can be emulated with two techniques:
For example,
- PCRE
a+b+c+=\K\d+
(demo) = .NET (?<=a+b+c+=)\d+
or a+b+c+=(\d+)
(and grab Group 1 value)
- PCRE
^[^][]+\K.*
(demo) = .NET (?<=^[^][]+)(?:\[.*)?$
(demo) or (better here) ^[^][]+(.*)
(demo).
The problem with the second example is that [^][]+
can match the same text as .*
(these patterns overlap) and since there is no clear boundary between the two patterns, just using a lookbehind is not actually working and needs additional tricks to make it work.
Capturing group approach is universal here and should work in all situations.
Since \K
makes the regex engine "forget" the part of a match consumed so far, the best approach here is to use a capturing group to grab the part of a match you need to obtain after the left-hand context:
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
var text = "Text 4000751111115425";
var result = Regex.Match(text, @"(?<!\d)\d{6}(\d+)(?=\d{4}(?!\d))")?.Groups[1].Value;
Console.WriteLine($"Result: '{result}'");
}
}
See the online C# demo and the regex demo (see Table tab for the proper result table). Details:
(?<!\d)
- a left-hand digit boundary
\d{6}
- six digits
(\d+)
- Capturing group 1: one or more digits
(?=\d{4}(?!\d))
- a positive lookahead that matches a location that is immediately followed with four digits not immediately followed with another digit.