Home > Blockchain >  Remove quotes around specific string with ReGex Python module?
Remove quotes around specific string with ReGex Python module?

Time:09-16

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?

CodePudding user response:

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] '
  • Related