Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I highlight regex matches in Python?

Tags:

python

editor

How might I highlight the matches in regex in the sentence? I figure that I could use the locations of the matches like I would get from this:

s = "This is a sentence where I talk about interesting stuff like sencha tea."
spans = [m.span() for m in re.finditer(r'sen\w+', s)]

But how do I force the terminal to change the colors of those spans during the output of that string?

like image 606
guidoism Avatar asked Dec 07 '22 19:12

guidoism


1 Answers

There are several terminal color packages available such as termstyle or termcolor. I like colorama, which works on Windows as well.

Here's an example of doing what you want with colorama:

from colorama import init, Fore
import re

init() # only necessary on Windows
s = "This is a sentence where I talk about interesting stuff like sencha tea."
print(re.sub(r'(sen\w+)', Fore.RED + r'\1' + Fore.RESET, s))
like image 116
Nicholas Riley Avatar answered Dec 28 '22 04:12

Nicholas Riley