Python 中的正则表达式删除冒号前的所有大写字符

Regex in Python to remove all uppercase characters before a colon

我有一个文本,我想删除冒号之前的所有大写连续字符。我只是想出了如何删除冒号本身之前的所有字符;这导致当前输出如下所示。

输入文字

text = 'ABC: This is a text. CDEFG: This is a second text. HIJK: This is a third text'

期望输出:

 'This is a text. This is a second text. This is a third text'

当前代码&输出:

re.sub(r'^.+[:]', '', text)

#current output
'This is a third text'

这可以用单行正则表达式来完成,还是我需要遍历每个 character.isupper() 然后实现正则表达式?

您可以使用

\b[A-Z]+:\s*
  • \b 防止部分匹配的单词边界
  • [A-Z]+: 匹配 1+ 个大写字符 A-Z 和一个 :
  • \s* 匹配可选的空白字符

Regex demo

import re

text = 'ABC: This is a text. CDEFG: This is a second text. HIJK: This is a third text'
print(re.sub(r'\b[A-Z]+:\s*', '', text))

输出

This is a text. This is a second text. This is a third text