so I have a quick question that I cannot figure out.
I have some lines that I want to parse for example:
a = a/2; b*= a/4*2; float c += 4*2*sin(2);And what I want is to get the assigned variable name of the assignment. So, in this case I woule like to retrieve a, b, c.
I have the following regex:
match = re.search(r'\b(?:float)?(.*)(?:(\+|-|\*|\\)? =)',line)
When I print out m.group(1) it would return a, b *, c +.
I cannot figure out why it also captures the operator before =, could someone explain?
You have a preceding greedy capture with the (.*) and you're allowing your operator-capture to be optional (with the ending ?); With this, the greedy-capture is the one that's bringing in the operator instead of letting it fall-through to the group matching the =.
Try changing the greedy-capture to be only what is acceptable there. From the looks of it, it could only be alpha-numeric values and spaces (numeric is a guess, so that could be dropped if not needed):
\b(?:float\s+)?([a-zA-Z0-9]+)\s*(?:(\+|-|\*|\\)? =)
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