python - regex for matching text between two characters while ignoring backslashed characters
<p>I am trying to use python to get text between two dollar signs ($), but the dollar signs should <strong>not</strong> start with a backslash i.e. \$ (this is for a LaTeX rendering program). So if this is given</p>

<pre><code>$\$x + \$y = 5$ and $3$ 
</code></pre>

<p>This is what should be outputted</p>

<pre><code>['\$x + \$y = 5', ' and ', '3']
</code></pre>

<p>This is my code so far:</p>

<pre><code>def parse_latex(text):
    return re.findall(r'(^|[^\\])\$.*?[^\\]\$', text)
print(parse_latex(r'$\$x + \$y = 5$ and $3$'))
</code></pre>

<p>But this is what I get:</p>

<pre><code>['', ' ']
</code></pre>

<p>I am not sure how to proceed from here.</p>

<p>You can use this lookaround based regex that excluded escaped characters:</p>

<pre><code>&gt;&gt;&gt; text = r'$\$x + \$y = 5$ and $3$'
&gt;&gt;&gt; re.findall(r'(?&lt;=\$)([^$\\]*(?:\\.[^$\\]*)*)(?=\$)', text)
['\\$x + \\$y = 5', ' and ', '3']
</code></pre>

<p><a href="https://regex101.com/r/zA7zE2/1" rel="nofollow">RegEx Demo</a></p>

<p><a href="http://ideone.com/7xzBwE" rel="nofollow">Code Demo</a></p>

<p><strong>RegEx Breakup:</strong></p>

<pre><code>(?&lt;=\$)           # Lookbehind to assert previous character is $
(                 # start capture group
   [^$\\]*        # match 0 or more characters that are not $ and \
   (?:            # start non-capturing group
      \\.         # match \ followed any escaped character
      [^$\\]*     # match 0 or more characters that are not $ and \
   )*             # non-capturing group, match 0 or more of this non-capturing group
)                 # end capture group
(?=\$)            # Lookahead to assert next character is $
</code></pre>

python regex escaping