简体   繁体   中英

How do I insert space before capital letter if and only if previous letter is not capital?

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?

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'

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

  • ([AZ]) Capture captital AZ in group 1
  • (?=[AZ][az]) Positive lookahead, assert what is on the right is an uppercase and a lowercase az
  • | Or
  • ([az]) Capture lowercase az in group 2
  • (?=[AZ]) Positive lookahead, assert what is on the right is uppercase AZ

Regex demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM