0

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?

Michael Hutter
  • 1,064
  • 13
  • 33
  • Because `$` matches a position before the final newline in a string. Since the second `.*?` is non-greedy, the `$` is tried first, and only if it does not match, `.*?` is expanded to advance to the next position, hence, `$` matches earlier. Use `\z` instead of `$` to get consistent behavior. – Wiktor Stribiżew Sep 14 '18 at 08:35
  • 1
    Thank you - \z was the solution - even to my now updated question. – Michael Hutter Sep 14 '18 at 09:09

0 Answers0