pistacchio
pistacchio

Reputation: 58893

Python regex split case insensitive in 2.6

I have the following code that works in Python 2.7:

entry_regex = '(' + search_string + ')'
entry_split = re.split(entry_regex, row, 1, re.IGNORECASE)

I need to make it work in Python 2.6 as well as in Python 2.7 and 2.6 re.split doesn't accept a flag (re.IGNORECASE) as forth parameter. Any help? Thanks

Upvotes: 7

Views: 4434

Answers (3)

Susam Pal
Susam Pal

Reputation: 34224

Create a re.RegexObject using re.compile() and then call it's split() method.

Example:

>>> re.compile('XYZ', re.IGNORECASE).split('fooxyzbar')
['foo', 'bar']

Upvotes: 3

Bill Gribble
Bill Gribble

Reputation: 1797

You can just add (?i) to the regular expression to make it case insensitive:

>>> import re
>>> reg = "(foo)(?i)"
>>> re.split(reg, "fOO1foo2FOO3")
['', 'fOO', '1', 'foo', '2', 'FOO', '3']

Upvotes: 15

pistacchio
pistacchio

Reputation: 58893

Oh, found it by myself, I can compile it to a Regex Object:

entry_regex = re.compile('(' + search_string + ')', re.IGNORECASE)
entry_split = entry_regex.split(row, 1)

Upvotes: 0

Related Questions