title: An optional element in C# RegEx matching expression
body: <p>How to make 'test2' an optional element in the following C# RegEx expression getting 'test1' value parsed out correctly when 'test2' element is missing?</p>
  
  <pre><code> StringBuilder sb = new StringBuilder();
   sb.AppendLine("    test1=123 any text in between  ");
   sb.AppendLine(" some ");
   sb.AppendLine(" more ");
   sb.AppendLine(" text in between ");
   sb.AppendLine("    test2=456   ");
   sb.AppendLine("    test1=789  some text .. test2=012   ");
  
   Regex regex = new Regex(@"test1=(?&lt;test1&gt;(\d+))((.|\s)+?)(test2=(?&lt;test2&gt;(\d+)))");
  
   MatchCollection matches = regex.Matches(sb.ToString());
   foreach (Match match in matches)
   {
       Group test1 = match.Groups["test1"];
       Group test2 = match.Groups["test2"];                
       System.Console.WriteLine("Test1 = {0}, Test2 = {1}", test1.Value, test2.Value);
   }
  </code></pre>
  
  <p>Thank you.</p>
  
  <hr>
  
  <p>@Oded - I reply here as I can't get comment formatted properly and as my reply is longer than allowed by StackOverflow comment text length:</p>
  
  <hr>
  
  <p>Thank you. Proposed in your second reply RegEx expression results in the following output:</p>
  
  <pre><code> Test1 = 123, Test2 = 
   Test1 = 789, Test2 =
  </code></pre>
  
  <p>It's not quite correct.
  And your first reply RegEx expression results in  </p>
  
  <pre><code> Test1 = 123, Test2 = 456
   Test1 = 789, Test2 = 012
  </code></pre>
  
  <p>test output. That's is correct.  </p>
  
  <p>But if I change  </p>
  
  <pre><code>sb.AppendLine("    test1=789  some text .. test2=012   ");
  </code></pre>
  
  <p>to  </p>
  
  <pre><code>sb.AppendLine("    test1=789  some text .. test52=012   ");
  </code></pre>
  
  <p>then the test result output will have just one line  </p>
  
  <pre><code>Test1 = 123, Test2 = 456
  </code></pre>
  
  <p>and I wanted it to be  </p>
  
  <pre><code> Test1 = 123, Test2 = 456
   Test1 = 789, Test2 =
  </code></pre>
  
  <p>in that case.</p>