Python to detect latex mathematics using regular expressions or other methods
<p>I want to detect if a long text string (input from "somewhere") contains mathematical expressions <a href="https://en.wikibooks.org/wiki/LaTeX/Mathematics" rel="nofollow">encoded in LaTeX</a>. This means searching for substrings (denoted <code>...</code> in what follows) enclosed inside either of:</p>

<ol>
<li><code>$...$</code></li>
<li><code>\[...\]</code></li>
<li><code>\(...\)</code></li>
<li><code>\begin{displaymath} ... \end{displaymath}</code></li>
</ol>

<p>There are some variations of item 3 with other keywords than <code>displaymath</code>, and there may be a whitespace inside the brace, etc., but I suppose I can figure out the rest once I get (1), (2), (3) working.</p>

<p>For (1), I suppose I can do the following:</p>

<pre><code>import re
if re.search(r"$(\w+)$", str):
  (do something)`
</code></pre>

<p>But I am having problems with the others, especially when it has the <code>\</code>. Help would be appreciated.</p>

<p>The python version should be 2.7.12 but ideally code that works for both versions 2.x and 3.x will be preferred.</p>

<p>You need to escape <code>\</code>,<code>[</code>,<code>]</code>,<code>{</code>,<code>}</code>,<code>(</code>,<code>)</code> as they have special meaning in regular expression. </p>

<p>So, you need to add an extra <code>\</code> before them, when you want to match them literally.  </p>

<p>For your second pattern, use:</p>

<pre><code>\\\[(.+?)\\\]
</code></pre>

<p>For third pattern, use:</p>

<pre><code>\\\((.+?)\\\)
</code></pre>

<p>For fourth pattern,</p>

<pre><code>\\begin\{displaymath\}(.+?)\\end\{displaymath\}
</code></pre>

<p>You can see the demo for the fourth pattern <a href="https://regex101.com/r/xG8mA8/1" rel="nofollow">here</a>.</p>

python string-matching