Home > Back-end >  Add text into string between single quotes using regexp
Add text into string between single quotes using regexp

Time:12-20

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 (\033[92m for green and \033[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 '\033[92mquoted text\033[0m' to display."
result3 = "I have '\033[92msome quotes\033[0m' plus some more text and '\033[92msome other quotes\033[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?

CodePudding user response:

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

res = re.sub(r"'([^']*)'", r"'\033[92m\1\033[0m'", s)

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

  • Related