python - 不要替换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_true
或comment_false
。
接下来,我想fword
用replace_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
我怎样才能做到这一点?
解决方案
尝试正则表达式:(?:^|(?<=\s))don(?=,|\.|\s|\Z)
推荐阅读
- vb.net - 如何打印受密码保护的访问报告?
- youtube-api - 使用 Youtube API V3 进行短语搜索
- discord - args.join 不是函数
- android - 如何在 Android WebView 上检测到同一页面上另一个部分的链接
- laravel - LARAVEL 8 - 我无法查看存储文件夹中的图像
- android - 如何在 Android 中获取图像的属性,如阴影、中间色调和高光?以及如何在 Android 中操作这些属性?
- wordpress - WordPress SSO - Azure AD B2C - 注册并登录用户流程 - 如何直接链接到注册页面?
- javascript - 如何为访问 HTML 和 CSS 属性的 javascript 文件中的函数提供参数?
- python - 无法使用 python 代码运行 .bat 文件:ImportError:无法导入所需的依赖项:numpy:
- qt - 无法进入 Qt 源代码