Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whitespace at the end of line is not ignored by python regex

Tags:

python

regex

The leading spaces are ignored but the trailing ones are not in the below regular expression code. It's just a "Name = Value" string but with spaces. I thought the \s* after the capture would ignore spaces.

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

What am I missing?

like image 820
sambha Avatar asked Dec 30 '25 21:12

sambha


1 Answers

You're getting trailing spaces because of greedy nature of .+.

You can use this regex to correctly capture your value:

>>> re.search(r"\s*(Name)\s*=\s*(.+?)\s*$", line).groups()
('Name', 'Peppa Pig')

\s*$ ensures we are capturing value before trailing white spaces at end.

like image 64
anubhava Avatar answered Jan 02 '26 11:01

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!