regex删除匹配的单词和连续的单词

2024-06-17 17:54:17 发布

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

我想删除单词Dr及其连续单词。
例如

输入

Financial disclosure of Dr Kucher
Patient 1 had adverse events and dr Bodendieck supposes that patient 1 does not tolerate milk
Drug accountability log and patient compliance.

在上面的输入模式中,我想删除所有以粗体突出显示的文本

输出

Financial disclosure of
Patient 1 had adverse events and supposes that patient 1 does not tolerate milk
Drug accountability log and patient compliance.

我使用的模式
/[(D|d)r]\s*(?=\w+)

根据我的理解
[(D | D)r]应匹配“Dr”或“Dr”
\s*应匹配空格
(?=\w+])应与紧接的连续单词匹配。在

参考模式
http://regex101.com/r/eU5yT8/2

然而,上述模式并不匹配 我是组建正则表达式的新手。请帮助我理解我的错了。谢谢


Tags: andofthat模式events单词financialhad
1条回答
网友
1楼 · 发布于 2024-06-17 17:54:17

它应该是:

re.sub(r'\b[Dd]r\s+\w+', '', txt)

当你包装在(?=...)中时,它将向前看,但不会像the documentation那样,Isaac (?=Asimov)只有在后面跟'Asimov'时,Isaac (?=Asimov)才会匹配'Isaac '。这意味着它将不匹配'Asimov'

^{pr2}$

另外,您还需要[Dd]r,这意味着D或{},后跟{},或者{}。在

\b将指定一个单词边界,否则,它将在单词末尾匹配dr(如果我们有这样一个单词):

>>> re.sub(r'[Dd]r\s*\w+', '', 'xdr test')
'x'

您需要\s+,否则它将与单词中间的dr匹配:

>>> re.sub(r'\b[Dd]r\s*\w+', '', 'drug')
''

相关问题 更多 >