Save EACH regex match to a new txt file (batch)?
Question: I basically need a program/script that will search a file for regex matches
and then save each match to a newly created text file (ie. match_01.txt,
match_02.txt, match_03.txt, etc.). NB: it must support multiline matching!

**EDIT :**

This is what I tried using Josha's help (thx:):

I get an error when I try this

**Python Script:**

    
    
    import re
    pattern = re.compile(r'(?s)(?<=Sample)(.*?)(?=EndSample)', flags=re.S)
    with open('test.txt', 'r') as f:
        matches = pattern.findall(f.read())
    
    for i, match in enumerate(matches):
        with open('Split/match{0:04d}.txt'.format(i), 'w') as nf:
            nf.write(match)
    

**Command Prompt:**

    
    
    C:\Test\python test.py
    Traceback (most recent call last):
      File "test.py", line 31, in <module>
        nf.write(match)
    TypeError: expected a character buffer object
    

test.txt looks something like this:

Sample A1 ... ... ... ... ... EndSample

Sample B4 ... ... ... ... ... EndSample

Sample X6 ... ... ... ... ... EndSample

So I need to match everything between "Sample" and "EndSample" (hundreds of
lines in-between) and write each match to its own txt file. So far it only
works if my regex pattern is ie. "Sample". There is 15 matches and it does
create 15 txt files in the Split folder but they all contain just the word
Sample and nothing more. Multiline still not working looks like.. And if my
regex is this:

> (?s)(Sample)(.*?)

then it also gives me the same error as above. Its like it doesnt like (.*?)
Strange..?


Answer: In Python (assuming matches do not span lines):

    
    
    import re
    pattern = re.compile(r'(?s)(?<=Sample)((?:.+?)?)(?=EndSample)', flags=re.S)  # Your regex goes here
    with open('path/to/your/file.txt', 'r') as f:
        matches = pattern.findall(f.read())
    
    for i, match in enumerate(matches):
        with open('/path/to/your/match{0:04d}.txt'.format(i), 'w') as nf:
            nf.write(match)
    

