Question

I have a list of words that need to be made human readable, such as FirstName to First Name, LastName to Last Name, and in some cases, acronyms like ARBs to remain as is. The latter was recently introduced and has caused a display issue since our regular expression returns AR Bs. Here's what we have, which I know is insufficient for acronyms:

([A-Z][a-z]+)

I've found other expressions on SO and on other sites that are able to work with acronyms, however they work on strings where the acronym is within the string rather than being the entire string. I can do simple regular expressions, but this is too tricky for my skills. I would provide other examples for testing if I had them, but all of the strings work fine except the new one, ARBs. Thank you.

Update: Here's the code usage

string friendlyName = Regex.Replace(field.Name, "([A-Z][a-z]+)", " $1", RegexOptions.Compiled).Trim();
Was it helpful?

Solution

Wouldn't [A-Z]+[a-z]* do it? That should match one or more upper-case letters followed by zero or more lower-case letters. So ARBs would remain a single entity, but CamelCase would be split into Camel Case.

OTHER TIPS

How about this?

[A-Z][a-z]+|[A-Z]

A string/paragraph/sentence including Acronyms can be converted to Human readable sentences/string. I was just trying for formatting of Pascal Cased string, i investigated more and tried even to convert Acronyms in to Understandable format.

Test Data:

Input: "QWERTYSomeThing OmitTRYSomeThing MayBeWorkingFYI"

Output: "QWERTY Some Thing Omit TRY Some Thing May Be Working FYI"

Code: Pass Input String to Method Given Below.

    private static string FormatPascalAndAcronym(string input)
    {
        var builder = new StringBuilder(input[0].ToString());
        if (builder.Length > 0)
        {
            for (var index = 1; index < input.Length; index++)
            {
                char prevChar = input[index - 1];
                char nextChar = index + 1 < input.Length ? input[index + 1] : '\0';

                bool isNextLower = Char.IsLower(nextChar);
                bool isNextUpper = Char.IsUpper(nextChar);
                bool isPresentUpper = Char.IsUpper(input[index]);
                bool isPrevLower = Char.IsLower(prevChar);
                bool isPrevUpper = Char.IsUpper(prevChar);

                if(!string.IsNullOrWhiteSpace(prevChar.ToString()) && 
                    ((isPrevUpper&& isPresentUpper && isNextLower) || 
                    (isPrevLower&&isPresentUpper&&isNextLower)||
                    (isPrevLower&&isPresentUpper&&isNextUpper)))
                {
                    builder.Append(' ');
                    builder.Append(input[index]);
                }
                else{
                builder.Append(input[index]);
                }
            }
        }
        return builder.ToString();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top