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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With