Search code examples
pythonpython-3.xregexpython-re

Python regex replace words within brackets


How to replace word within brackets with empty string for repetitive words?

import re

resource_path = '/mdm/v1/{appId}/templates/{templateId}'
clean_resource_path = re.sub(r"\s*\{[^()]*\}$", '', resource_path)

print(clean_resource_path)

I get output as /mdm/v1/ but ideally I want output as /mdm/v1/templates. I know the my regex is replacing everything between {} with empty quotes, but I want only to the next available quote.


Solution

  • import re
    resource_path = '/mdm/v1/{appId}/templates/{templateId}'
    clean_resource_path = re.sub(r"/{\w*}*", '', resource_path)
    
    print(clean_resource_path)
    

    output

    /mdm/v1/templates