Top

Django: Highlight Search Results

Aug 10, 2020 | 1168 views

#Python #Django


Solution refer to below links


Python re.sub() case insensitive replace coding example: 


In [54]: re.sub('(%s)'%re.escape('hE'), r'<abc>\g<1></abc>', 'hello', flags=re.IGNORECASE)
Out[54]: '<abc>he</abc>llo'
In [56]: re.sub('(%s)'%re.escape('hE.'), r'<abc>\g<1></abc>', 'he.llo', flags=re.IGNORECASE)
Out[56]: '<abc>he.</abc>llo'

Or another version (Here we exclude URL replacement from HTML text): 

    pattern = re.compile('(^%s|[\s]%s|%s[\s])' % tuple([re.escape(word),]*3), re.IGNORECASE)
highlighted = pattern.sub(r'<span class="highlight">\g<1></span>', highlighted)

Regex resource refer to:


Leave a comment

0 comments