Add text into string between single quotes using regexp

Question:

I am trying to use Python to add some escape characters into a string when I print to the terminal.

import re

string1 = "I am a test string"
string2 = "I have some 'quoted text' to display."
string3 = "I have 'some quotes' plus some more text and 'some other quotes'.

pattern = ... # I do not know what kind of pattern to use here

I then want to add the console color escape (33[92m for green and 33[0m to end the escape sequence) and end characters at the beginning and end of the quoted string using something like this:

result1 = re.sub(...)
result2 = re.sub(...)
result3 = re.sub(...)

with the end result looking like:

result1 = "I am a test string"
result2 = "I have some '33[92mquoted text33[0m' to display."
result3 = "I have '33[92msome quotes33[0m' plus some more text and '33[92msome other quotes33[0m'.

What kind of pattern should I use to do this, and is re.sub an appropriate method for this, or is there a better regex function?

Asked By: SandPiper

||

Answers:

You could use a capturing group to capture negated ' within single quotes.

res = re.sub(r"'([^']*)'", r"'33[92m133[0m'", s)

See this demo at regex101 or a Python demo at tio.run (1 refers first group)

Answered By: bobble bubble
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.