15
votes

If I want to take

"hi, my name is foo bar"

and split it on "foo", and have that split be case insensitive (split on any of "foO", "FOO", "Foo", etc), what should I do? Keep in mind that although I would like to have the split be case insensitive, I also DO want to maintain the case sensitivity of the rest of the string.

So if I have:

test = "hi, my name is foo bar"

print test.split('foo')

print test.upper().split("FOO")

I would get

['hi, my name is ', ' bar']
['HI, MY NAME IS ', ' BAR']

respectively.

But what I want is:

['hi, my name is ', ' bar']

every time. The goal is to maintain the case sensitivity of the original string, except for what I am splitting on.

So if my test string was:

"hI MY NAME iS FoO bar"

my desired result would be:

['hI MY NAME iS ', ' bar']
3
I don't understand the application of such a split. What would FOO be in real cases? Are you extracting a person's name or something else? - Aditya
One possible example: SQL scripts can use a separator to separate batches (f.e. "go" by default in SQL manager). This separator isn't understood by the SQL engine itself, only by the shell. So when you run such a script from a python module, you need to split the file on "go" to run the separate batches in series (case insensitive ofc). - sanderd17

3 Answers

30
votes

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']
>>>
1
votes

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

enter image description here

-1
votes

You can also search for something and get the startposition of the keyword. I would recommend that and cut it with "substring" method out. (I am from C# so i dont know whats the method in this language)