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).
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 (...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.