using System.Text.RegularExpressions;
using System.Collections.Generic;
public static void Main()
var text = "PartySiteEO_AddressLine1";
var formatText = GetFormattedName(text);
Console.WriteLine(formatText.ToUpper());
var result = string.Concat(GetFormattedName2(text));
Console.WriteLine(result.ToUpper());
public static string GetFormattedName(string originalText)
var invalidCharsRgx = new Regex("[^_a-zA-Z0-9]");
var whiteSpace = new Regex(@"(?<=\s)");
var startsWithLowerCaseChar = new Regex("^[a-z]");
var firstCharFollowedByUpperCasesOnly = new Regex("(?<=[A-Z])[A-Z0-9]+$");
var upperCaseInside = new Regex("(?<=[A-Z])[A-Z]+?((?=[A-Z][a-z])|(?=[0-9]))");
var putUndescoreBeforeUpperCase = new Regex(@"(?<!_|^)([A-Z])");
var text = invalidCharsRgx.Replace(whiteSpace.Replace(originalText, "_"), string.Empty)
.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries)
.Select(w => startsWithLowerCaseChar.Replace(w, m => m.Value.ToUpper()))
.Select(w => firstCharFollowedByUpperCasesOnly.Replace(w, m => m.Value.ToLower()))
.Select(w => upperCaseInside.Replace(w, m => m.Value.ToLower()));
var resultText = string.Concat(text);
resultText = putUndescoreBeforeUpperCase.Replace(resultText, "_$1");
public static IEnumerable<char> GetFormattedName2(string formattedName)
bool isFirstCharacter = true;
bool isPreviousUpper = false;
foreach(char c in formattedName)
if(Char.IsUpper(c) && !isPreviousUpper)
if(!isFirstCharacter && !isPreviousUpper) yield return '_';
isFirstCharacter = false;
isPreviousUpper = Char.IsUpper(c) || c == '_';