pythonregex

Remove part of a string in python with regex


I'm trying to use a regex to remove off my string all text from & after ":q=". I have used the code below but it only removes "":q="". Is anyone be able to help me?

import re

string = ":example1:q=dfgghp-yoirjl78/-"

print(string)

x = re.sub(r':q=.?','', string)

Solution

  • Just replace ? with * to capture all characters.

    import re
    
    string = ":example1:q=dfgghp-yoirjl78/-"
    print(string)
    
    x = re.sub(r':q=.*','', string)
    print(x)