How to alternate capitalizations with RegEX?

33 Views Asked by At

I need to change a sentence to have alternating capitalizations! Having trouble making it ignore the spacebar inputs...

input: the quick brown fox jumps over the lazy dog
output: tHe QuIcK bRoWn FoX jUmPs OvEr ThE lAzY dOg

I tried the following:

input: ([\w\s])([\w\s]?)
output: upper(\1)\2

1

There are 1 best solutions below

0
Wiktor Stribiżew On

You can use

import re
text = "the quick brown fox jumps over the lazy dog"
print( re.sub(r"(\S)(\s*)(\S)", lambda x: f'{x.group(1).lower()}{x.group(2)}{x.group(3).upper()}', text) )
# tHe QuIcK bRoWn FoX jUmPs OvEr ThE lAzY dOg

See the Python demo.

The (\S)(\s*)(\S) regex matches and captures a non-whitespace char into Group 1, then captures zero or more whitespaces into Group 2 and then captures any whitespace into Group 3. The f'{x.group(1).lower()}{x.group(2)}{x.group(3).upper()}' replacement concatenates a lowercase Group 1 value, the whitespaces in Group 2 and an uppercased value in Group 3.