【问题标题】:Python Re.Sub Function Usage IssuePython Re.Sub 函数使用问题
【发布时间】:2020-12-30 22:55:58
【问题描述】:

我需要有关此 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;
}

【问题讨论】:

    标签: python regex syntax substitution


    【解决方案1】:

    使用

    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
    

    【讨论】:

    • 感谢您的回答,但例如,如果我使用这样的语法 result = re.sub(regex[i],"abc", test_str, 0) 这里的 regex[i] 每次迭代都不同在循环。那么我该如何在这种情况下提出您的解决方案?
    • @AbdulHannan fr"\b{regex[i]}\b(?!\.h\b)"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 2011-08-05
    • 1970-01-01
    相关资源
    最近更新 更多