Home > Mobile >  In Python, find all occurrences of a group of characters in a string and remove the last character f
In Python, find all occurrences of a group of characters in a string and remove the last character f

Time:10-09

I have a large string and I would like to find all occurrences of one or more consecutive right curly brackets (for any number of curly brackets) that are surrounded by double quotes, and remove the last double quote.

I thought I could do this with a regex and "re", and so far I have the following, however I'm not sure what to replace "???" with. I'm not even sure if re with a regex is the correct way to go in the first place:

import re
my_string= r'abc"}"abc"}}"abc"}}}"abc"}}}}"abc"{abc}"'
result = re.sub(r'"} "', ???, my_string)
print(result)

... my desired result is this:

abc"}abc"}}abc"}}}abc"}}}}abc"{abc}"

How can I achieve this in Python? Thank you!

CodePudding user response:

You could use a capture group to keep what is before the closing double quote.

("} )"

And replace with capture group 1.

Regex demo

Example

import re

my_string= r'abc"}"abc"}}"abc"}}}"abc"}}}}"abc"{abc}"'
result = re.sub(r'("} )"', r"\1", my_string)
print(result)

Output

abc"}abc"}}abc"}}}abc"}}}}abc"{abc}"
  • Related