title: Multiline regex match retrieving line numbers and matches
body: <p>I'm attempting to iterate over all lines in a file to match a pattern that could;</p>
  <ol>
  <li>Occur anywhere in the file</li>
  <li>Occur multiple times in the same file</li>
  <li>Occur multiple times on the same line</li>
  <li>The string I'm searching for could be spread across multiple lines for one regex pattern</li>
  </ol>
  <p>An example input would be;</p>
  <pre><code>new File()
  new
  File()
  there is a new File()
  new
      
      
      
  File()
  there is not a matching pattern here File() new
  new File() test new File() occurs twice on this line
  </code></pre>
  <p>Example output would be;</p>
  <pre><code>new File() Found on line 1  
  new File() Found on lines 2 &amp; 3 
  new File() Found on line 4 
  new File() Found on lines 5 &amp; 9 
  new File() Found on line 11
  new File() Found on line 11 
  6 occurrences of new File() pattern in test.txt (Filename)
  </code></pre>
  <p>The regex pattern would look something like;</p>
  <pre><code>pattern = r'new\s+File\s*\({1}\s*\){1}'
  </code></pre>
  <p>Looking at the docs <a href="https://docs.python.org/3/howto/regex.html" rel="nofollow noreferrer">here</a>, I can see match, findall and finditer all return matches at the beginning of strings but I don't see a way of using the search function which looks at any location for a regex where the string we're searching for is over multiple lines (Number four in my requirements above).</p>
  <p>Simple enough to match more than one occurence of the regex per line with;</p>
  <p>example input:</p>
  <pre><code>line = &quot;new File() new File()&quot;
  </code></pre>
  <p>Code:</p>
  <pre><code>i = 0
  matches = []
  while i &lt; len(line):
      while line:
          matchObj = re.search(r&quot;new\s+File\s*\({1}\s*\){1}&quot;, line, re.MULTILINE | re.DOTALL)
          if matchObj:
              line = line[matchObj.end():]
              matches.append(matchObj.group())
  
  print(matches)
  </code></pre>
  <p>Prints the following matches - Not including line numbers ect for now:</p>
  <pre><code>['new File()', 'new File()']
  </code></pre>
  <p>Is there a way to do what I'm looking for with Python's regex?</p>