Skip to content

Instantly share code, notes, and snippets.

@blacknon
Created February 9, 2022 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blacknon/92264704589d300e708996ec1456d739 to your computer and use it in GitHub Desktop.
Save blacknon/92264704589d300e708996ec1456d739 to your computer and use it in GitHub Desktop.
pythonでregex matchしたとこをハイライトさせる場合のサンプルコード(どっかからのコピペだった…はず)
#!/usr/bin/env python3
# -*- encoding: UTF-8 -*-
import re
colourFormat = '\033[{0}m'
colourStr = colourFormat.format(32)
resetStr = colourFormat.format(0)
s = "This is a sentence where I talk about interesting stuff like sencha tea."
lastMatch = 0
formattedText = ''
for match in re.finditer(r'sen\w+', s):
start, end = match.span()
formattedText += s[lastMatch: start]
formattedText += colourStr
formattedText += s[start: end]
formattedText += resetStr
lastMatch = end
formattedText += s[lastMatch:]
print(formattedText)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment