Remove characters after three consecutive capital letters

Viewed 65

I am trying to remove all characters after 3 consecutive capital letters so for example: Crowd_Cheer_Large_Football_Game_Applause_OCP-0098-14.wav

Explosion_Artillery_DET-0020-256_Stereo.wav

Should become :

Crowd_Cheer_Large_Football_Game_Applause_OCP

Explosion_Artillery_DET

In Python I have tried that:

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)

But apparently I can't use (?<= ... ) like that so I don't know how to do !

Thanks !

2 Answers

You can use re.sub() this way:

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

We are matching substring from and including 3 uppercase alphabets and replace them with the same 3 uppercase alphabets.

Please try this out. Hope this helps

import re

text1 = 'Crowd_Cheer_Large_Football_Game_Applause_OCP-0098-14.wav'
text2 = 'Explosion_Artillery_DET-0020-256_Stereo.wav'

x = re.search('([A-Z]){3}',text1)
y = re.search('([A-Z]){3}',text2)

index = x.start() + 3
print(text1[:index:])

index = y.start() + 3
print(text2[:index:])
Related