Reputation: 9001
Is there any way to search and replace certain strings, but also watch out for similar strings, and not replace those?
for example, if i have
self.a
self.b
self.c
self.d
self.e
self.f
self.g
and i wanted
self.a
self.__b
self.c
self.__d
self.__e
self.f
self.g
and i want to add __
to some of the variables to make them private, but not others, how would i do it, short of changing each individually, or changing all of them and then undoing the ones i dont want? my program has a large number of variables and uses each of them very often, so i dont want to go through the code myself.
Upvotes: 0
Views: 177
Reputation: 1144
Regular expressions are your friend here. They are a little intensive to the beginner, though. To accomplish the goal in the above example use the python command:
import re
pattern = r'(self\.)(b|d|e)\s'
result = re.sub(pattern, '\1__\2', source)
This takes every instance of a string starting with 'self.' followed by b, d, or e, and replaces it with a 'self.__' followed by the correct string.
Upvotes: 1
Reputation: 208705
In addition to creating another script to perform the replacement, you can probably do this in your editor. For example if you use Vim typing the following should do what you want:
:%s/self\.\(b\|d\|e\)/self.__\1/g
Upvotes: 1
Reputation: 940
Back up your script. Create a new script and import re
, then re.sub() your original script. Run a unit test on the regex'd script to ensure functionality.
Upvotes: 1
Reputation: 76985
Python's re module has a function called re.sub
which will replace everything matching a pattern with something else.
You can also use regular expressions from Perl, awk, sed, etc. depending on your preferences. Just search and replace based on whatever patterns you might want to match and change.
Upvotes: 3