re.findall() returning the wrong values when using optionals
<p>I'm following along in a tutorial and I seem to be stuck on what seems to be an easy thing to do:</p>

<pre><code>numRegex = re.compile(r'\d+(\s+\w+)?')
spam = numRegex.findall("my address is   999 Street Ave City CA 95014 x")
print(len(spam))
print(spam)
</code></pre>

<p>this returns <code>[' Street', ' x']</code> which is obviously wrong as it should be <code>['999 Street', '95014 x']</code>.</p>

<p>You are capturing the group wrongly. Try:</p>

<pre><code>numRegex = re.compile(r'(\d+(?:\s+\w+)?)')
</code></pre>

<p>Or, </p>

<pre><code>numRegex = re.compile(r'\d+(?:\s+\w+)?')
</code></pre>

<p><code>\d+(\s+\w+)?</code> seeks for the whole pattern, but only matches <code>(\s+\w+)</code> part because, this is the capturing group.</p>

<p>You need to match the whole pattern. So, you should add a parenthesis  over the whole pattern to match the whole pattern as captured group.</p>

<p>Now, You have one nested capturing group <code>(\s+\w+)?</code>. You need to make it a non capturing group. So, Add a <code>?:</code> inside the parenthesis to get the effect.  </p>

python regex