首页 > 解决方案 > 不要替换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是 incomment_truecomment_false

接下来,我想fwordreplace_with.

结果字符串应该是:

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)

然而,对于这个问题,它们是不够的,因为诸如“不要”或 Carl&Don 之类的收缩部分是匹配的。这个问题不是简单的空格检查,因为我只需要转义一些符号。

请参阅此处的示例: https ://regexr.com/42bc8

我怎样才能做到这一点?

标签: pythonregex

解决方案


尝试正则表达式:(?:^|(?<=\s))don(?=,|\.|\s|\Z)

演示


推荐阅读