Home > Blockchain >  Convert lower camelCase to PascalCase in c#?
Convert lower camelCase to PascalCase in c#?

Time:10-15

I need to convert camelcase keys to Pascal key and I got good solution from stackoverflow. But the issue is I don't know how to exclude . in conversion.

Please find the below example:

var input= "customer.presentAddress.streetName";

Expected Output is

var output= "Customer.PresentAddress.StreetName";

PlayGround : Please click here

CodePudding user response:

I have a code that can solve your problem given that every string is a string array for c# we can do it here:

var teste = "customer.presentAddress.streetName".Split(".");

List<string> result = new List<string>();

foreach (var x in teste)
{
    result.Add(string.Concat(x[0].ToString().ToUpper(), x.AsSpan(1)));
}


Console.WriteLine(String.Join(".", result));

I converted it to a static method so you can use it wherever you need:

public static class ConvertPatternString
{
    public static string ToPascalCase(this string value) =>
    value switch
    {
        null => throw new ArgumentNullException(nameof(value)),
        "" => throw new ArgumentException($"{nameof(value)} cannot be empty", nameof(value)),
        _ => string.Concat(value[0].ToString().ToUpper(), value.AsSpan(1))
    };

    public static string ToPascalCaseWithSeparator(this string value, string separator) =>
    value switch
    {
        null => throw new ArgumentNullException(nameof(value)),
        "" => throw new ArgumentException($"{nameof(value)} cannot be empty", nameof(value)),
        _ => string.Join(separator, value.Split(separator).Select(x => string.Concat(x[0].ToString().ToUpper(), x.AsSpan(1))))
    };
}

to use just do:

Console.WriteLine("customer.presentAddress.streetName".ToPascalCaseWithSeparator("."));

CodePudding user response:

An idea to use e.g. \b\p{Ll} (demo) for matching lower word's first letter and use a callback.

string output = Regex.Replace(input, @"\b\p{Ll}", match => match.Value.ToUpper());

See this C# demo at tio.run - \b is a word boundary and \p{Ll} matches lowercase letters.

CodePudding user response:

You might also assert that to the left is not a non whitespace char except for a dot, and then match a lowercase char a -z.

Then using Regex.Replace with a callback you can change that match to an uppercase char.

(?<![^\s.])[a-z]

Explanation

  • (?<! Negative lookbehind, assert what is directly to the legt is not
    • [^\s.] Match a single char other than a whitespace char or dot
  • ) Close lookbehind
  • [a-z] Match a single char a-z

Regex demo

CodePudding user response:

As per the @Hans Passant and @JamesS comments, I have rewritten the code :

public static string ToPascalCase(this string input)
        {
          return string.Join('.',input.Split('.').Select(x => ConvertToPascalCase(x)));
        }
        private static string ConvertToPascalCase(string input)
        {
            Regex invalidCharsRgx = new Regex(@"[^_a-zA-Z0-9]");
            Regex whiteSpace = new Regex(@"(?<=\s)");
            Regex startsWithLowerCaseChar = new Regex("^[a-z]");
            Regex firstCharFollowedByUpperCasesOnly = new Regex("(?<=[A-Z])[A-Z0-9] $");
            Regex lowerCaseNextToNumber = new Regex("(?<=[0-9])[a-z]");
            Regex upperCaseInside = new Regex("(?<=[A-Z])[A-Z] ?((?=[A-Z][a-z])|(?=[0-9]))");

            // replace white spaces with undescore, then replace all invalid chars with empty string
            var pascalCase = invalidCharsRgx.Replace(whiteSpace.Replace(input, "_"), string.Empty)
                // split by underscores
                .Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries)
                // set first letter to uppercase
                .Select(w => startsWithLowerCaseChar.Replace(w, m => m.Value.ToUpper()))
                // replace second and all following upper case letters to lower if there is no next lower (ABC -> Abc)
                .Select(w => firstCharFollowedByUpperCasesOnly.Replace(w, m => m.Value.ToLower()))
                // set upper case the first lower case following a number (Ab9cd -> Ab9Cd)
                .Select(w => lowerCaseNextToNumber.Replace(w, m => m.Value.ToUpper()))
                // lower second and next upper case letters except the last if it follows by any lower (ABcDEf -> AbcDef)
                .Select(w => upperCaseInside.Replace(w, m => m.Value.ToLower()));

            return string.Concat(pascalCase);
        }
  • Related