Regular expression matching all but a string
<p>I need to find all the strings matching a pattern with the exception of two given strings. </p>

<p>For example, find all groups of letters with the exception of <code>aa</code> and <code>bb</code>. Starting from this string:</p>

<pre><code>-a-bc-aa-def-bb-ghij-
</code></pre>

<p>Should return:</p>

<pre><code>('a', 'bc', 'def', 'ghij')
</code></pre>

<p>I tried with <a href="http://pythex.org/?regex=-(%5Cw.*%3F)(%3F%3D-)&amp;test_string=-a-bc-def-ghij-&amp;ignorecase=0&amp;multiline=0&amp;dotall=0&amp;verbose=0" rel="nofollow">this regular</a> expression that captures 4 strings. I thought I was getting close, but (1) it doesn't work in Python and (2) I can't figure out how to exclude a few strings from the search. (Yes, I could remove them later, but my real regular expression does everything in one shot and I would like to include this last step in it.)</p>

<p>I said it doesn't work in Python because I tried this, expecting the exact same result, but instead I get only the first group:</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; re.search('-(\w.*?)(?=-)', '-a-bc-def-ghij-').groups()
('a',)
</code></pre>

<p>I tried with negative look ahead, but I couldn't find a working solution for this case.</p>

<p>You can make use of negative look aheads.</p>

<p>For example,</p>

<pre><code>&gt;&gt;&gt; re.findall(r'-(?!aa|bb)([^-]+)', string)
['a', 'bc', 'def', 'ghij']
</code></pre>

<hr>

<ul>
<li><p><code>-</code> Matches <code>-</code></p></li>
<li><p><code>(?!aa|bb)</code> Negative lookahead, checks if <code>-</code> is not followed by <code>aa</code> or <code>bb</code></p></li>
<li><p><code>([^-]+)</code> Matches ony or more character other than <code>-</code></p></li>
</ul>

<hr>

<p><strong>Edit</strong></p>

<p>The above regex will not match those which start with <code>aa</code> or <code>bb</code>, for example like <code>-aabc-</code>. To take care of that we can add <code>-</code> to the lookaheads like, </p>

<pre><code>&gt;&gt;&gt; re.findall(r'-(?!aa-|bb-)([^-]+)', string)
</code></pre>

python regex