-1

The solution can apparently be this:

$string = 'TodayILiveInTheUSAWithSimon';
$regex = '/(?<!^)((?<![[:upper:]])[[:upper:]]|[[:upper:]](?![[:upper:]]))/';
$string = preg_replace( $regex, ' $1', $string );

But this case "TodayILiveInTheUSAWithSimonUSA" does not work well because it returns "Today I Live In The USA With Simon US A" the last letter appears separated. Do you know a complete solution?

kusflo
  • 61
  • 9
  • 1
    Possible duplicate of [RegEx to split camelCase or TitleCase (advanced)](https://stackoverflow.com/questions/7593969/regex-to-split-camelcase-or-titlecase-advanced) – Sebastian Proske Feb 01 '18 at 15:16
  • You may use: [`(?<=[A-Z])[A-Z]{2}(*SKIP)(*F)|(?<=[A-Za-z])(?=[A-Z])`](https://regex101.com/r/X3gIix/1/) – anubhava Feb 01 '18 at 15:32

3 Answers3

1
(?<!^)(?![[:upper:]]$)((?<![[:upper:]])[[:upper:]]|[[:upper:]](?![[:upper:]]))

Added in a negative lookahead to make sure it isn't matching the capital at the end of the string too.

The only times you'll want to separate this is if you're ending on a one letter word anyway, which is unlikely, so shouldn't have too much backlash

KyleFairns
  • 2,947
  • 1
  • 15
  • 35
0

If you just want to skip all 3 uppercase letters then using PHP (PCRE) you may be able to use this regex:

(?<=[A-Z])[A-Z]{2}(*SKIP)(*F)|(?<=[A-Za-z])(?=[A-Z])

Code:

$re = '/(?<=[A-Z])[A-Z]{2}(*SKIP)(*F)|(?<=[A-Za-z])(?=[A-Z])/';

$result = preg_replace($re, ' ', $str);

Explanation:

  • (?<=[A-Z])[A-Z]{2}(*SKIP)(*F): If we match 2 uppercase letters and have a uppercase letter at previous position then skip (fail) that pattern
  • |: OR
  • (?<=[A-Za-z])(?=[A-Z]): If have any letter at previous position and have a uppercase letter at next position
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Regex: (?:[A-Z]+|[A-Z][a-z]+)\K(?=[A-Z]) Substitution: " " (space)

Details:

  • (?:) Non capturing group
  • [] Match a single character present in the list
  • + Matches between one and unlimited times
  • | Or
  • \K Resets the starting point of the reported match.
  • (?=) Positive Lookahead

Regex demo

Code:

$text = 'TodayILiveInTheUSAWithSimon';
$text = preg_replace("/(?:[A-Z]+|[A-Z][a-z]+)\K(?=[A-Z])/", " ", $text);
print_r($text);

Output: Today I Live In The USA With Simon

Srdjan M.
  • 3,310
  • 3
  • 13
  • 34