Why does this regex result in four items?
<p>I want to split a string by <code></code>, <code>-&gt;</code>, <code>=&gt;</code>, or those wrapped with several spaces, meaning that I can get two items, <code>she</code> and <code>he</code>, from the following strings after being split:<br>
<code>"she he", "she  he", "she he ", "she  he  ", "she-&gt;he", "she  -&gt;he", "she=&gt;he", "she=&gt;  he", "  she-&gt;  he  ", "  she   =&gt;  he \n"</code></p>

<p>I have tried using this:</p>

<pre><code>re.compile("(?&lt;!^)((\\s*[-=]&gt;\\s*)|[\\s+\t])(?!$\n)(?=[^\s])").split(' she  -&gt; he \n')
</code></pre>

<p>What I get is a list with four items: <code>[' she', '  -&gt; ', '  -&gt; ', 'he \n']</code>.</p>

<p>And for this,  </p>

<pre><code>re.compile("(?&lt;!^)((\\s*[-=]&gt;\\s*)|[\\s+\t])(?!$\n)(?=[^\s])").split('she he')
</code></pre>

<p>I get this: <code>['she', ' ', None, 'he']</code>.</p>

<p>Why are there four items? And how can I get only two without the middle two?</p>

<p>Each time you are using parentheses "()" you are creating a capturing group. A capturing group is a part of a match. A match always refers to the complete regex string. That is why you are getting 4 results. </p>

<p>Documentation says: <a href="https://docs.python.org/2/library/re.html" rel="nofollow">"If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list."</a></p>

<p>You could try making the groups "non-capturing" as Rawing suggested. Do this by simply prepending "?:" inside the parentheses you do not want to be captured. </p>

<p>I would just leave out the parentheses altogether:</p>

<pre><code>res = re.compile("\\s*[-=]&gt;\\s*|\\s*").split(' she  -&gt; he \n')
res = filter(None, res)
res = list(res)
</code></pre>

<p>Output:</p>

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

python regex split