Replace special characters with words in python
<p>For the following string:</p>

<p><code>s = The \r\n sun shines, that's fine [latex]not\r\nt for \r\n everyone[/latex] and if it rains, \r\nit Will Be better.</code>.</p>

<p>If I want to replace <code>\n\r</code> by <code>' '</code> between <code>[latex]</code> and <code>[/latex]</code>, I can use:</p>

<pre><code>re.sub("\[latex\][^]]*\[/latex\]", lambda x:x.group(0).replace('\r\n',' '), s)
</code></pre>

<p>which works fine.</p>

<p>However, if the input is:</p>

<pre><code>s = some\r\nthing\r\n[latex]\\[\x08egin{array}{*{20}{l}}\r\n{{\rm{dA}} = {\rm{wdy}}:}\\\r\n{{\rm{dF}} = {\rm{P}}\\;{\rm{dA}} = \rho {\rm{g}}\\left( {{\rm{H}}-{\rm{y}}} \right)\\;\\omega \\;{\rm{dy}}}\r\n\\end{array}\\][/latex]\r\n
</code></pre>

<p>and I use the same expression, nothing gets replaced.
Any idea what I'm doing wrong ?</p>

<p>The problem is due to presence of <code>]</code> before <code>[/latex]</code> in second input. Also better to use raw strings for your input and regex.</p>

<p>You can use this regex for search:</p>

<pre><code>\[latex\].*?\[/latex\]
</code></pre>

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

<p><strong>Code:</strong></p>

<pre><code>&gt;&gt;&gt; s = r"some\r\nthing\r\n[latex]\\[\x08egin{array}{*{20}{l}}\r\n{{\rm{dA}} = {\rm{wdy}}:}\\\r\n{{\rm{dF}} = {\rm{P}}\\;{\rm{dA}} = \rho {\rm{g}}\\left( {{\rm{H}}-{\rm{y}}} \right)\\;\\omega \\;{\rm{dy}}}\r\n\\end{array}\\][/latex]\r\n"
&gt;&gt;&gt; print re.sub(r"\[latex\].*?\[/latex\]", lambda x:x.group(0).replace(r'\r\n', ' '), s)
some\r\nthing\r\n[latex]\\[\x08egin{array}{*{20}{l}} {{\rm{dA}} = {\rm{wdy}}:}\\ {{\rm{dF}} = {\rm{P}}\\;{\rm{dA}} = \rho {\rm{g}}\\left( {{\rm{H}}-{\rm{y}}} \right)\\;\\omega \\;{\rm{dy}}} \\end{array}\\][/latex]\r\n
</code></pre>

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

python regex