santosh
santosh

Reputation: 4139

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.

Upvotes: 1

Views: 143

Answers (1)

user13824946
user13824946

Reputation:

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

Upvotes: 5

Related Questions