Split a string with few delimiters python

Viewed 66

My goal is to split a given text by uppercase letters and underscore.

For example, for the given strings:

s = 'Where_IsKCR'

This should return ['Where', 'Is', 'KCR']. The KCR is together because it is an entity.

I'm trying to use regex and my code looks like this:

s='Where_IsKCR'
list=[]
tmp = (re.split('_|([A-Z][^A-Z]*)',s))
num=len(tmp)
i=0
while(i<num):
    if(tmp[i]==''):
        i=i+1
    elif(len(tmp[i])>1):
        list.append(tmp[i])
        i=i+1
    elif(len(tmp[i])==1):
        word=""
        while(len(tmp[i])<=1):
            if(i==num-1):
                break
            elif(tmp[i]==''):
                i=i+1
                continue
            else:
                word = word + tmp[i]
                i=i+1
        list.append(word)
return list

So, for the given string s the code returns ['Where_', 'Is', 'KCR']. The code does not split for the underscore. Any ideas why?

1 Answers

You can use

list(filter(None, re.split(r'_|(?<=[^A-Z])(?=[A-Z])', text)))

See the regex demo. Details:

  • _ - an underscore (it is consumed, thus, it will be removed when splitting)
  • | - or
  • (?<=[^A-Z])(?=[A-Z]) - a location that is immediately preceded with a char other than an uppercase ASCII letter and immediately followed with an uppercase ASCII letter.

See a Python demo:

import re
text = r'Where_IsKCR'
print( list(filter(None, re.split(r'_|(?<=[^A-Z])(?=[A-Z])', text))) )
# => ['Where', 'Is', 'KCR']
Related