Split by a word (case insensitive)
You can use the re.split
function with the re.IGNORECASE
flag (or re.I
for short):
>>> import re
>>> test = "hI MY NAME iS FoO bar"
>>> re.split("foo", test, flags=re.IGNORECASE)
['hI MY NAME iS ', ' bar']
>>>
This is not the exact answer but the solution based on the question. After searching awhile on the net I implemented the following.
This is my custom tag (see how to do it).
from django.template.defaultfilters import register
from django.utils.html import escape
from django.utils.safestring import mark_safe
@register.simple_tag
def highlight(string, entry, prefix, suffix):
string = escape(string)
entry = escape(entry)
string_upper = string.upper()
entry_upper = entry.upper()
result = ''
length = len(entry)
start = 0
pos = string_upper.find(entry_upper, start)
while pos >= 0:
result += string[start:pos]
start = pos + length
result += prefix + string[pos:start] + suffix
pos = string_upper.find(entry_upper, start)
result += string[start:len(string)]
return mark_safe(result)
It accepts unsafe string and returns the escaped result.
Use it this way:
<span class="entityCode">{% highlight entity.code search_text '<span class="highlighted">' '</span>' %}</span>
I use a nested <span>
to inherit all the style. And it shows something like