2

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).

1 Answer 1

3

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 (...)
Sign up to request clarification or add additional context in comments.

3 Comments

Maybe throw in a #, a $ and a ^ there too..?
That's great and enough for my purpose, thanks. But I'm just curious to know how to provide the same number of spaces in the new string as were in the original?
@user1768576 Yes, you can do this as well. I have updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.