Background:
Match MyMatch1 = Regex.Match("Line1\nLine2\n", "^.$", RegexOptions.Singleline);
Match MyMatch2 = Regex.Match("Line1\nLine2\n", "^.?$", RegexOptions.Singleline);
MyMatch1.Groups[0].Value.Length => "Line1\nLine2\n"
MyMatch2.Groups[0].Value.Length => "Line1\nLine2"
Why does the non-greedy variant (.*?
) remove the newline char at the end of the string?
Because my Regular Expression starts with ^
and ends with $
the non-greedy variant should also take the full string.
Problem:
As I have read here a $
is also finding a \n
.
string sStr1 = "Line1\nLine2\nOptionalLine\n";
string sStr2 = "Line1\nLine2\n";
string sRegex = "^(.*?)(OptionalLine\n)?$"; // <= I need non-greedy here
Match MyMatch3 = Regex.Match(sStr1, sRegex, RegexOptions.Singleline);
Match MyMatch4 = Regex.Match(sStr2, sRegex, RegexOptions.Singleline);
MyMatch3.Groups[1].Value => 'Line1\nLine2\n'
MyMatch3.Groups[2].Value => 'OptionalLine3\n'MyMatch4.Groups[1].Value => 'Line1\nLine2' <= I want to have a newline here!
MyMatch4.Groups[2].Value => ''
What can I do to get the newline even if the OptionalLine is missing?
How should I write my Regex to achieve this?