【问题标题】:Regex in Python to remove all uppercase characters before a colonPython中的正则表达式删除冒号前的所有大写字符
【发布时间】:2026-01-22 06:25:01
【问题描述】:

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

输入文字

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() 然后实现正则表达式?

【问题讨论】:

  • 您可以使用+?*?(惰性正则表达式) 来查找最小匹配字符串。
  • 从所需的输出中我们可以看到您删除了连续的大写字母、冒号和至少一个空格。您能否更清楚地说明目标
  • @MarkSouls 但这并不能解决问题,因为在这种情况下它不匹配大写字符,并且锚会阻止多个匹配
  • @Thefourthbird 是的,我只是把它作为一种相关的提示。

标签: python regex string text python-re


【解决方案1】:

你可以使用

\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

【讨论】:

    最近更新 更多