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>Although a regex solution was asked for, I would argue that this problem can be solved easier with simpler python functions, namely string splitting and filtering:</p>

<pre><code>input_list = "-a-bc-aa-def-bb-ghij-"
exclude = set(["aa", "bb"])
result = [s for s in input_list.split('-')[1:-1] if s not in exclude]
</code></pre>

<p>This solution has the additional advantage that <code>result</code> could also be turned into a generator and the result list does not need to be constructed explicitly. </p>

python regex