Given a variable name such as myvariable, what regex could be used to replace (refactor) references to it with another variable name myreplacementvariable
e.g.
addr = &myvariable;
should turn into
addr = &myreplacementvariable;
BUT
int myvariable2 = 0;
should be left alone (because it’s a different variable name that happens to contain the name of myvariable)
I am looking for a line or two of Python, probably with Regex.
Note: I am aware parsing C is incredibly difficult and am not looking for anything that thinks about scope. I also forsee char *mystr = "myvariable"; causing problems but I can work around that.
Thanks in advance
Maybe this helps:
Note that I escaped the ampersand by putting it within the [].
You could also escape it with two backslashes:
Edit:
Here’s a re.sub version based on discussion in the comments:
This pattern will have the same result as:
I’m using the parentheses for matching the ampersand at the start and the possible semicolon at the end. Then I’m using the \1 and \2 to put these matches back in within the replacement string. Note that this result would be similar to using: value.replace(“&”+oldVarName, “&”+newVarName)
EDIT:
This is probably closer to what you need.
It replaces every instance starting with an ampersand AND contains the whole old variable name and doesn’t contain any of the characters afterwards that are within [A-Za-z0-9_].
(That last part is any valid character for in a variable name in C, after the first character which is required to start with: [A-Za-z_]. This is also mentioned in the answer by ‘nhahtdh’)
Using what nhahtdh provided as an example this would be a shorter version of the last example:
Since it was new to me when writing this answer and it got mixed up in the comments by myself in this answer I’m adding this as information: The r in front of the strings like r”\1″ turn the string into a raw string.