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>If you can just strip your input string. From your description, all you need is to split the words on either <code>\s+</code> or <code>\s*-&gt;\s*</code> or <code>\s*=&gt;\s*</code></p>

<p>So here is my solution:</p>

<pre><code>p = re.compile(r'\s*[-=]&gt;\s*|\s+')
input1 = "she he"
input2 = " she  -&gt; he \n".strip()

print p.split(input1)
print p.split(input2)
</code></pre>

<p>Your output would be just 'she' and 'he':</p>

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

python regex split