In Python, find all occurrences of a group of characters in a string and remove the last character from each occurence

Question:

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!

Asked By: Yob

||

Answers:

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}"
Answered By: The fourth bird
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.