Extract specific section from LaTeX file with python
<p>I have a set of LaTeX files. I would like to extract the "abstract" section for each one: </p>

<pre class="lang-tex prettyprint-override"><code>\begin{abstract}

.....

\end{abstract}
</code></pre>

<p>I have tried the suggestion here: <a href="http://stackoverflow.com/questions/30752351/how-to-parse-latex-file">How to Parse LaTex file</a></p>

<p>And tried :</p>

<pre><code>A = re.findall(r'\\begin{abstract}(.*?)\\end{abstract}', data)
</code></pre>

<p>Where data contains the text from the LaTeX file. But <code>A</code> is just an empty list. Any help would be greatly appreciated!</p>

<p><code>.*</code> does not match newlines unless the re.S flag is given:</p>

<pre><code>re.findall(r'\\begin{abstract}(.*?)\\end{abstract}', data, re.S)
</code></pre>

<h3>Example</h3>

<p>Consider this test file:</p>

<pre class="lang-tex prettyprint-override"><code>\documentclass{report}
\usepackage[margin=1in]{geometry}
\usepackage{longtable}

\begin{document}
Title maybe
\begin{abstract}
Good stuff
\end{abstract}
Other stuff
\end{document}
</code></pre>

<p>This gets the abstract:</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; data = open('a.tex').read()
&gt;&gt;&gt; re.findall(r'\\begin{abstract}(.*?)\\end{abstract}', data, re.S)
['\nGood stuff\n']
</code></pre>

<h3>Documentation</h3>

<p>From the <a href="https://docs.python.org/2/library/re.html#re.DOTALL" rel="nofollow"><code>re</code> module's webpage</a>:</p>

<blockquote>
  <p>re.S<br> re.DOTALL<br></p>
  
  <p>Make the '.' special character match any character at
  all, including a newline; without this flag, '.' will match anything
  except a newline.</p>
</blockquote>

python regex latex