title: Limit number of lines in text by a regular expression
body: <p>In any programming language I know how to efficiently limit the number of lines in a given file or string, that is not the issue here. However in this case I am looking to do this by a regular expression. In this pattern I am using only <code>\n</code> <em>newline characters.</em> I have no need for others such as <code>\r</code> <em>carriage returns</em>.</p>
  
  <pre><code>(?:(?:\n)?[^\n]*){0,3}
  </code></pre>
  
  <p>The above regular expression explained:</p>
  
  <pre><code>(?:       group, but do not capture (between 0 and 3 times)-
   (?:      group, but do not capture (optional)
    \n      '\n' (newline)
   )?       end of grouping
   [^\n]*   any character except: '\n' (newline) (0 or more times)
  ){0,3}    end of grouping
  </code></pre>
  
  <p>Now using this regular expression in a string such as..</p>
  
  <pre><code>In this line is foo bar and baz
  In this line is bar and foo
  In this line is baz and bar
  In this line we have foo
  In this line we have bar and foo and baz
  In this line we have foobar
  In this line we have foo
  In this line we have foo and bar
  In this line we have bar and baz and foo
  </code></pre>
  
  <p>This will return lines <code>1-3</code> with no issue.</p>
  
  <p>In the above string, lines <code>7</code>, <code>8</code>, and <code>9</code> all contain the word <code>foo</code> all by itself whether it is in the beginning, the middle or the end of the string. </p>
  
  <p>Now my question is how could I implement either a look ahead or look behind to search a string and find <code>3</code> lines of text in a row that all have that same keyword <code>foo</code> by itself and not as a prefix of a word or combined in another word? So therefore it would match only lines <code>7-9</code> and not <code>1-6</code>.</p>