Home > other >  Python regex to match all occurrences between curly brackets, not just the last occurence
Python regex to match all occurrences between curly brackets, not just the last occurence

Time:10-16

In my Python code, I have the following string:

Here is my string with "\"The Address\", I want to replace only the selection between the brackes: {Here is my string between \"The Address\" and \"something\" else}. Thank you!

I would like to replace ALL occurrences of \" that occur ONLY between curly brackets with ". So my desired result is

Here is my string with "\"The Address\", I want to replace only the selection between the brackes: {Here is my string between "The Address" and "something" else}. Thank you!

I'm trying r'({.*)(\\")(.*})' with a substitution of \1"\3 as given here: https://regex101.com/r/NWSDS6/1

However that is only selecting/replacing the very last \" , how do I select/replace ALL of the occurrences between the curly braces?

EDIT after comment: Here is a variation of the string with an extra curly bracket after the word "replace":

Here is my string with "\"The Address\", I want to replace} only the selection between the brackes: {Here is my string between \"The Address\" and \"something\" else}. Thank you!

In this variation, the first two occurrences are selected however I would like them to be omitted as they do not occur BETWEEN TWO curly brackets. Is that possible?

CodePudding user response:

You can use this solution using lambda:

s = r'Here is my string with "\"The Address\", I want to replace} only the selection between the brackes: {Here is my string between \"The Address\" and \"something\" else}. Thank you!'

s = re.sub(r'{[^}]*}', lambda m: m.group().replace(r'\"', '"'), s)

console.log(s)

Output:

Here is my string with "\"The Address\", I want to replace} only the selection between the brackes: {Here is my string between "The Address" and "something" else}. Thank you!

Here:

  • {[^}]*} matches string between {...}
  • m.group().replace(r'\"', '"') replaces all \" with " inside the matched text.
  • Related