I need help with this re.sub function.
For example, if I wanted to replace “string” with “abc”
but I want #include <string.h> to remain the same so that the syntax does not get disturbed and all the other “string” variables get replaced with “abc”. How can I write the re.sub function?
The Python code is:
result = re.sub("string","abc", test_str, 0)
test_str is this
#include <string.h>
#include <stdlib.h>
char *Function(unsigned char *string, unsigned char *key)
{
unsigned int i, j;
for (i = 0; i < s(string); i++)
{
string[i] = ~ string[i];
}
return string;
}
Advertisement
Answer
Use
result = re.sub(r"bstringb(?!.hb)", "abc", test_str)
See proof
Explanation
--------------------------------------------------------------------------------
b the boundary between a word char (w) and
something that is not a word char
--------------------------------------------------------------------------------
string 'string'
--------------------------------------------------------------------------------
b the boundary between a word char (w) and
something that is not a word char
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
. '.'
--------------------------------------------------------------------------------
h 'h'
--------------------------------------------------------------------------------
b the boundary between a word char (w)
and something that is not a word char
--------------------------------------------------------------------------------
) end of look-ahead