不要替换python中包含撇号或&的单词

2024-04-19 12:02:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下设置:

fword = "don"
comment_true = "Don is bad. Don't eat nails. Carl&Don. Don&Carl. Don, Don."
comment_false = "Don't do this"
replace_with = "[ANONYMISED]"

首先,我想检查fword是在comment_true还是comment_false中。你知道吗

接下来,我想用replace_with替换fword。你知道吗

结果字符串应为:

comment_true:

"[ANONYMISED] is bad. Don't eat nails. Carl&Don. Don&Carl. [ANONYMISED], [ANONYMISED]."

comment_false:

"Don't do this"

目前我正在使用的第一个任务是:

 True if re.search(r'\b%s\b' % fword, comment) else False

对于我正在使用的第二个任务

re.compile(r"\b%s\b" % fword, re.IGNORECASE).sub(replace_with, comment)

但是对于这个问题,它们是不够的,因为像don't或Carl&don这样的收缩部分是匹配的。这个问题不是简单的空格检查,因为我只需要转义一些符号。你知道吗

请看下面的示例: https://regexr.com/42bc8

我怎样才能做到这一点?你知道吗


Tags: refalsetrueiswithcommentreplacebad