Whitespace at the end of line is not ignored by python regex
<p>The leading spaces are ignored but the trailing ones are not in the below regular expression code. It's just a <code>"Name = Value"</code> string but with spaces. I thought the <code>\s*</code> after the capture would ignore spaces.</p>

<pre><code>import re
line = "  Name =  Peppa Pig  "
match = re.search(r"\s*(Name)\s*=\s*(.+)\s*", line)
print(match.groups())
&gt;&gt;&gt;('Name', 'Peppa Pig   ')  # Why extra spaces after Pig!
</code></pre>

<p>What am I missing?</p>

<p>The last <code>.+</code> grabs the whole rest of the line (as <code>.</code> matches any char but a newline), and then starts backtracking, checking if the subsequent subpatterns should match. Since the subsequent subpattern is <code>\s*</code> that can match an empty string (it matches 0+ whitespaces), this pattern successfully matches at the end of the string, and a valid match with trailing whitespaces is returned.</p>

<p>See <a href="https://regex101.com/r/dL6eN0/1" rel="nofollow">your regex demo</a> (pay special attention at Step 15):</p>

<p><a href="http://i.stack.imgur.com/rsB6L.png" rel="nofollow"><img src="http://i.stack.imgur.com/rsB6L.png" alt="enter image description here"></a></p>

<p>You may let Python do the <code>strip</code> job inside a list comprehension and simplify the regex to just <code>(Name)\s*=(.+)</code>:</p>

<pre><code>import re
line = "  Name =  Peppa Pig  "
match = [(x,y.strip()) for x,y in re.findall(r"(Name)\s*=(.+)", line)]
print(match)
</code></pre>

<p>See <a href="http://ideone.com/OSXzdM" rel="nofollow">Python demo</a></p>

python regex