Python regex to replace a double newline delimited paragraph containing a string
<p>Define a paragraph as a multi-line string delimited on both side with double new lines ('\n\n'). if there exist a paragraph which contains a certain string ('BAD'), i want to replace that paragraph (i.e. any text containing BAD up to the closest preceding and following double newlines) with some other token ('GOOD'). this should be with a python 3 regex.</p>

<p>i have text such as:</p>

<pre><code>dfsdf\n
sdfdf\n
\n
blablabla\n
blaBAD\n
bla\n
\n
dsfsdf\n
sdfdf
</code></pre>

<p>should be:</p>

<pre><code>dfsdf\n
sdfdf\n
\n
GOOD\n
\n
dsfsdf\n
sdfdf
</code></pre>

<p>Here you are:</p>

<pre><code>/\n\n(?:[^\n]|\n(?!\n))*BAD(?:[^\n]|\n(?!\n))*/g
</code></pre>

<p>OK, to break it down a little (because it's nasty looking):</p>

<ul>
<li><code>\n\n</code> matches two literal line breaks.</li>
<li><code>(?:[^\n]|\n(?!\n))*</code> is a non-capturing group that matches either a single non-line break character, or a line break character that isn't followed by another. We repeat the entire group 0 or more times (in case <code>BAD</code> appears at the beginning of the paragraph).</li>
<li><code>BAD</code> will match the literal text you want. Simple enough.</li>
<li>Then we use the same construction as above, to match the rest of the paragraph.</li>
</ul>

<p>Then, you just replace it with <code>\n\nGOOD</code>, and you're off to the races.</p>

<p><a href="https://regex101.com/r/alaJMF/3" rel="nofollow">Demo on Regex101</a></p>

python regex