首页 > 解决方案 > 删除连续三个大写字母后的字符

问题描述

我试图删除 3 个连续大写字母后的所有字符,例如:Crowd_Cheer_Large_Football_Game_Applause_OCP-0098-14.wav

Explosion_Artillery_DET-0020-256_Stereo.wav

应该变成:

Crowd_Cheer_Large_Football_Game_Applause_OCP

爆炸_火炮_DET

在 Python 中,我尝试过:

import re
import string

text1 = 'Crowd_Cheer_Large_Football_Game_Applause_OCP-0098-14.wav'
text2 = 'Explosion_Artillery_DET-0020-256_Stereo.wav'
text1 = re.sub((?<='[A-Z]{3}'), '', text1)
text2 = re.sub((?<='[A-Z]{3}'), '', text2)
print (text1)
print (text2)

但显然我不能那样使用 (?<= ... ) 所以我不知道该怎么做!

谢谢 !

标签: python

解决方案


你可以re.sub()这样使用:

text1 = re.sub(r'([A-Z]{3}).*', '\\1', text1)
text2 = re.sub(r'([A-Z]{3}).*', '\\1', text2)

我们正在匹配来自 3 个大写字母(包括 3 个大写字母)的子字符串,并将它们替换为相同的 3 个大写字母。


推荐阅读