Reputation: 107
I have the text:
'SMThingAnotherThingBIGCapitalLetters'
and I want the output to be:
'SM Thing Another Thing BIG Capital Letters'
My regex now:
r"(\w)([A-Z])", r"\1 \2"
This works when I don't have 2 capital letters near eachother.
Output for my regex:
'S MThing Another Thing B I G Capital Letters'
So, I need regex to insert a space before a capital letter when next letter is small.
Anyone have an idea?
Upvotes: 1
Views: 1311
Reputation: 163457
You could use alternation with 2 capturing groups and replace with group1 group2 space
like r"\1\2 "
([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])
Explanation
([A-Z])
Capture captital A-Z in group 1(?=[A-Z][a-z])
Positive lookahead, assert what is on the right is an uppercase and a lowercase a-z|
Or([a-z])
Capture lowercase a-z in group 2(?=[A-Z])
Positive lookahead, assert what is on the right is uppercase A-ZUpvotes: 2
Reputation: 10030
You should use regular expressions carefully. They can easily transform to gargantuan monsters nobody can understand. You can solve your problem with simple loop instead of regexp:
a = 'SMThingAnotherThingBIGCapitalLetters'
result = a[0]
for i, letter in enumerate(a):
if letter.isupper() and (result[-1].islower() or a[i+1].islower()):
result += ' '
if i: result += letter
result
'SM Thing Another Thing BIG Capital Letters'
Upvotes: 4