How To Use RegEx To Put Space Between Words

I am trying to work out how to use RegEx to form a string that form a space before every capital letter that isn’t the first letter and also I want it to not add a space if it is one capital letter after the next. For example:
‘ThisIsASentence’ would be changed to ‘This Is A Sentence’
‘USAKeyboard’ would be changed to ‘USA Keyboard’


The first example could largely be carried out with a simple ReplaceAllB. The second would indeed require at the minimum a list of acronyms.

For i as integer = 65 to 90 TextArea1.Text = TextArea1.Text.ReplaceAllB(chr(i), " "+chr(i)) next

You can add a space before every capital letter which is either preceded or followed by a lowercase letter, but you will have problems with single letter words (I, A) if they coincide with a multiple capital letter acronym:


I would apply two RegExes. The first has search pattern code([A-Z])[/code] that is, lowercase then uppercase. The second has search pattern code([A-Z][a-z])[/code] to find two or more caps followed by a lowercase, with the break between the last two caps. Both of them happen to have the same replacement pattern, $1\\x20$2 (the \x20 is a space, and can be replaced by an actual space). Note that CaseSensitive must be set to True for this.

dim rx as new RegEx
rx.SearchPattern = "(?-i)[A-Z](?:[A-Z](?![^A-Z]))*"
rx.ReplacementPattern = " $&"
rx.Options.ReplaceAllMatches = true

s = rx.Replace( s )
s = s.Trim