Toby Wilson
Toby Wilson

Reputation: 1507

Regular expression to add a space before the last in a sequence of consecutive capital letters

Have given up on this after spending too much time trying to figure it out, and thought I'd see if someone else wants a go!

I need a regular expression that will insert a space before the last consecutive capital letter where there are more than two consecutive capital letters.

E.g's:

A = A
AB = AB
ABC = AB C
ABCD = ABC D
abCdefGHijkLMNop = abCdefGHijkLM Nop

Upvotes: 1

Views: 276

Answers (3)

kbdjockey
kbdjockey

Reputation: 897

This regexp will group:

([A-Z]{2,})([A-Z]+)

then you just have to output group 1, a space, group 2

Upvotes: 4

Rawling
Rawling

Reputation: 50134

The replacement

string output=Regex.Replace(input, @"(?<=[A-Z]{2})(?=[A-Z][^A-Z]|[A-Z]$)", " ");

"replaces" the zero-length point between the last two capital letters in a chain with a space, i.e. inserts a space.

Upvotes: 0

MikeM
MikeM

Reputation: 13641

string str = "ABC";
str = Regex.Replace(str, @"([A-Z]{2,})([A-Z])", "$1 $2"); 

Console.WriteLine(str);    // "AB C"

Upvotes: 0

Related Questions