title: Return the whole line that contains a match using regular expressions in c#
body: <p>Suppose I have the following string:</p>
  
  <pre><code>string input = "Hello world\n" + 
                 "Hello foobar world\n" +
                 "Hello foo world\n";
  </code></pre>
  
  <p>I have a regex pattern (as specified by the user of the tool I'm writing) of <code>"foobar"</code>.</p>
  
  <p>I want to return the entire line of each line in <code>input</code> that match the expression <code>foobar</code>.  So in this example, the output should be <code>Hello foobar world</code>.</p>
  
  <p>If the pattern were <code>"foo"</code>, I'd want to return:</p>
  
  <blockquote>
    <p>Hello foobar world<br/>
    Hello foo word</p>
  </blockquote>
  
  <p>Is this possible?</p>
  
  <p>The code I have is</p>
  
  <pre><code>string pattern = "foobar";
  Regex r = new Regex(pattern)
  foreach (Match m in r.Matches(input))
  {
      Console.WriteLine(m.Value);
  }
  </code></pre>
  
  <p>Running this will output:</p>
  
  <blockquote>
    <p>foobar</p>
  </blockquote>
  
  <p>Rather than:</p>
  
  <blockquote>
    <p>Hello foobar world</p>
  </blockquote>
  
  <p>If <code>string pattern = "foo";</code> then the output is:</p>
  
  <blockquote>
    <p>foo<br/>
    foo</p>
  </blockquote>
  
  <p>Rather than:</p>
  
  <blockquote>
    <p>Hello foobar world<br/>
    Hello foo world</p>
  </blockquote>
  
  <p>I've also tried:</p>
  
  <pre><code>// ...
  Console.WriteLine(m.Result("$_")); // $_ is replacement string for whole input
  // ...
  </code></pre>
  
  <p>But this results in the whole of <code>input</code> for each match in the string (when the pattern is <code>foo</code>):</p>
  
  <blockquote>
    <p>Hello world<br/>
    Hello foobar world<br/>
    Hello foo world<br/>
    Hello world<br/>
    Hello foobar world<br/>
    Hello foo world</p>
  </blockquote>