I have an expression that I want to extract the first part before the =
sign. However it doesn't work:
import re
re.sub('(.*?)=(.*?)', r'\1', 'F0=None')
This returns 'F0None'. Shouldn't it return the first captured group, i.e. 'F0' only?
re.sub
replaces the portion of the string that matched with the replacement. Because your second group is also optional (due to the ?
) your pattern is satifsied as soon as the =
is found, so the rest of the string falls into the "unmatched portion" (i.e. the second group is just a zero-length string). If you make the second group greedy so it grabs the whole rest of the string, it'll work how you expect:
>>> re.sub('(.*?)=(.*)', r'\1', 'F0=None')
'F0'
Also, if you don't actually want to do anything with it, the second group doesn't need to be a group at all:
>>> re.sub('(.*?)=.*', r'\1', 'F0=None')
'F0'