我有以下设置:
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
我怎样才能做到这一点?你知道吗
试试正则表达式:
(?:^|(?<=\s))don(?=,|\.|\s|\Z)
Demo
相关问题 更多 >
编程相关推荐