 <pre><code>import re # re.M means match across line boundaries # re.DOTALL means the . wildcard matches \n newlines as well pattern = re.compile('\\\\begin\{figure\}.*?\\\\end\{figure\}', re.M|re.DOTALL) # 'with' is the preferred way of opening files; it # ensures they are always properly closed with open("file1.tex") as inf, open("fileout.tex","w") as outf: for match in pattern.findall(inf.read()): outf.write(match) outf.write("\n\n") </code></pre> <p><strong>Edit:</strong> found the problem - not in the regex, but in the test text I was matching against (I forgot to escape the \b's in it).</p>