I’m searching for the best way to add a string to an existing string while I don’t want to replace the whole string.
self.fields_desc.append(BitField("foo", 0x3, 4))
sould be replaced by:
self.fields_desc.append(BitField("foo" + str(self.__class__.i), 0x3, 4))
Using which tool would allow me to do this with the less possible trouble? In vim I could do:
:%s/self.fields_desc.append(BitField("[a-zA-Z0-9]*", 0x[0-9]*, [0-9]*))/self.fields_desc.append(BitField("foo" + str(self.__class__.i), 0x3, 4))/g
But I don’t know how I would tell vim to not replace the regex I wrote. Could you give me a hand on this please?
Use capturing groups (note the “\” before the “(” and “)”, and the “\1”, “\2” etc):
changes:
to
Note:
*with+for the number matches: I doubt you want to matchself.fields_desc.append(BitField("foo", 0x,)etc.self.fields_desc.append(BitField("foo", 0x3...but sometimesself.fields_desc.append(BitField("foo",0x3orself.fields_desc.append(BitField("foo", 0x3, then add a*after the space characters. Although I’d suggest insteading standardising your code.See Regex grouping and The regex “dot”.
As sidyll says, it is probably better to learn to use the built-in character classes “\d”, “\w” (see Shorthand character classes) and so on:
This is both for brevity, and readability. Also, otherwise, readers will assume you have some special reason for defining your own character class (i.e., they will read it twice to make sure there’s not some unknown character in there).