There are two ways to solve this problem
Using PositiveLookBehind and Negative lookahead (answered by Wiktor)
Using Capture Groups which I discuss here.
Consider the regex below
(?:^\s*DEBUG\s+)*(.+)
with test data
DEBUG
How are you1?
DEBUG
How are you2?
How are you3?
_DEBUG How are you4?
I want to filter out the string DEBUG from the beginning if present. We created two groups.
Group-1: It is a non-capturing group (?:
^\s*DEBUG\s+)
* to capture string DEBUG from the beginning. This group is optional as it has * at the end.
Group-2: It is a capturing group that captures everything except what was captured in Group-1 using (
.+)
The regex below shows a black rectangle around part of the regex that comes in Group-2
The highlighted match are shown below
The c# code to get those value is below
string pattern = @"(?:^\s*DEBUG\s+)*(.+)";
Regex regex = new Regex(pattern);
var testInput=@"DEBUG How are you1?
DEBUG How are you2?
How are you3?
_DEBUG How are you4?";
var result = Regex.Matches(testInput,pattern,RegexOptions.Multiline);
result.Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToList()
.Dump();
Output: