title: Python to detect latex mathematics using regular expressions or other methods
body: <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>