Editor

Replace and Keep the Case

#345 · Strings · Advanced · 115 XP · about 20 min

A thoughtful find-and-replace changes "Cat" to "Dog", "CAT" to "DOG" and "cat" to "dog", so the text keeps its style. Write replace_keep_case(text, old, new) that replaces every occurrence of the phrase old in text with the phrase new, written in the style of that occurrence.

  • old and new are one or more words separated by single spaces, and a word is a run of English letters.
  • An occurrence is a piece of text that equals old when case is ignored, with no letter right before it and no letter right after it.
  • Occurrences are found from left to right, and after a replacement the search carries on after the replaced piece, so occurrences never overlap.

Each replacement copies the style of the occurrence it replaces. Use the first of these rules that fits:

  • The occurrence has no capital letters: write new in lowercase.
  • It has at least two letters and no lowercase letters: write new in capitals.
  • Every word in it is a capital followed only by lowercase letters: write every word of new that way.
  • Otherwise: write new exactly as it was given.

Examples

replace_keep_case('Cat and cat and CAT', 'cat', 'dog')
# returns 'Dog and dog and DOG'
replace_keep_case('Concatenate the cat.', 'cat', 'dog')
# returns 'Concatenate the dog.'
replace_keep_case('I love New York. NEW YORK never sleeps!', 'new york', 'los angeles')
# returns 'I love Los Angeles. LOS ANGELES never sleeps!'
replace_keep_case('My cAt', 'cat', 'iPhone')
# returns 'My iPhone'

A single capital letter such as "I" counts as a capitalized word, because capitals need at least two letters.

Constraints

  • text has at most 200,000 characters: English letters, spaces and punctuation, with no digits or underscores.
  • old and new have 1 to 5 words each.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.