Reputation: 193
I need to modify a C source file using a Python script. How would I change this string:
#define MY_STRING 0
to:
#define MY_STRING 1
using a Python regular expression?
Ideally, the solution would accommodate an unknown number of spaces before the numeric value.
(Basically I don't know how to specify the original string minus the numeric value in the new string).
Upvotes: 2
Views: 112
Reputation: 39355
Use \s+
between the digit and the text for arbitrary number of spaces.
code = re.sub('define MY_STRING\s+0', 'define MY_STRING 1', code);
If you want to keep the same amount of spaces before the digit like original string, then you have to capture it and then use it on replacement.
code = re.sub('(define MY_STRING\s+)0', "\\1 1", code);
## \\1 is the captured group on regex inside (...)
Upvotes: 3