Remove quotes around specific string with ReGex Python module?

Question:

How can i remove quotation marks around the phrase "Service Name" – "Users Connected: 359" – "Firstseen: 591230-EF" of only "Firstseen: 591230-EF", so it will become "Service Name" – "Users Connected: 359" – Firstseen: 591230-EF, using Regex?

Asked By: Raul Chiarella

||

Answers:

Replace the string surrounded by quotes with just the string. You can use a capture group in the regexp to get the string between the quotes.

text = '"Service Name" - "Users Connected: 359" - "Firstseen: 591230-EF"'
phrase = 'Firstseen: 591230-EF'
new_text = re.sub(f'"({phrase})"', r'1', text)
print(new_text)

Output:

"Service Name" - "Users Connected: 359" - Firstseen: 591230-EF

If you want to match something other than a fixed string, put that into phrase. For instance, you can match two different fixed strings with alternation:

phrase = 'Part 3|Data 4'

If you want to match any code after Firstseen, it would be

phrase = r'Firstseen: d+-[A-Z]+'
Answered By: Barmar
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.