Search code examples
pythonpython-re

Remove digits from a string when they are followed by a letter pattern


I have three strings as follows

ex1 = "All is good 24STREET"
ex2 = "Is this the weight 2.5OZ"
ex3 = "Feeling good 100pc"

I want to remove only the digits when they are followed by 'OZ' or 'pc' but not with others.

**results**
    ex1 = "All is good 24STREET"
    ex2 = "Is this the weight OZ"
    ex3 = "Feeling good pc"

I tried with 'str.replace('\d+', '')' but this removes all digits and also not the "dot"


Solution

  • import re
    
    ex1 = "All is good 24STREET"
    ex2 = "Is this the weight 2.5OZ"
    ex3 = "Feeling good 100pc"
    reg = re.compile(r'[\d.]+(?=OZ|pc)')
    print(reg.sub('', ex1))
    print(reg.sub('', ex2))
    print(reg.sub('', ex3))
    

    Output:

    All is good 24STREET

    Is this the weight OZ

    Feeling good pc