I'm attempting to iterate over all lines in a file to match a pattern that could;
- Occur anywhere in the file
- Occur multiple times in the same file
- Occur multiple times on the same line
- The string I'm searching for could be spread across multiple lines for one regex pattern
An example input would be;
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
Example output would be;
new File() Found on line 1
new File() Found on lines 2 & 3
new File() Found on line 4
new File() Found on lines 5 & 9
new File() Found on line 11
new File() Found on line 11
6 occurrences of new File() pattern in test.txt (Filename)
The regex pattern would look something like;
pattern = r'new\s+File\s*\({1}\s*\){1}'
Looking at the docs here, 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).
Simple enough to match more than one occurence of the regex per line with;
example input:
line = "new File() new File()"
Code:
i = 0
matches = []
while i < len(line):
while line:
matchObj = re.search(r"new\s+File\s*\({1}\s*\){1}", line, re.MULTILINE | re.DOTALL)
if matchObj:
line = line[matchObj.end():]
matches.append(matchObj.group())
print(matches)
Prints the following matches - Not including line numbers ect for now:
['new File()', 'new File()']
Is there a way to do what I'm looking for with Python's regex?