Skip to content

Instantly share code, notes, and snippets.

@un33k
Created March 27, 2012 21:56
Show Gist options
  • Select an option

  • Save un33k/2220739 to your computer and use it in GitHub Desktop.

Select an option

Save un33k/2220739 to your computer and use it in GitHub Desktop.
highlight needles in haystack -- search
def highlight_word(needles, haystack, cls_name='highlighted'):
regex = re.compile(r"(%s)" % "|".join(needles), re.I)
i = 0; out = ""
for m in regex.finditer(haystack):
out += "".join([haystack[i:m.start()],'<span class="%s">'%cls_name,haystack[m.start():m.end()],"</span>"])
i = m.end()
return mark_safe(out + haystack[i:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment