Python Re.Sub 函数使用问题

问题描述

我需要有关此 re.sub 函数的帮助。 例如,如果我想用“abc”替换“string” 但我希望 #include <string.h> 保持不变,这样语法就不会受到干扰,并且所有其他“字符串”变量都被替换为“abc”。如何编写 re.sub 函数

Python 代码是:

result = re.sub("string","abc",test_str,0)

test_str 是这个

#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;
}

解决方法

使用

result = re.sub(r"\bstring\b(?!\.h\b)","abc",test_str)

proof

说明

--------------------------------------------------------------------------------
  \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