Is there a better way to create acronym from upper letters in C#?

后端 未结 6 1499
日久生厌
日久生厌 2021-01-19 00:06

What is the best way to create acronym from upper letters in C#?

Example:

Alfa_BetaGameDelta_Epsilon

Expected r

6条回答
  •  遇见更好的自我
    2021-01-19 00:46

    By using MORE regexes :-)

    var ac = string.Join(string.Empty, 
                         Regex.Match("Alfa_BetaGameDelta_Epsilon", 
                                     "(?:([A-Z]+)(?:[^A-Z]*))*")
                              .Groups[1]
                              .Captures
                              .Cast()
                              .Select(p => p.Value));
    

    More regexes are always the solution, expecially with LINQ! :-)

    The regex puts all the [A-Z] in capture group 1 (because all the other () are non-capturing group (?:)) and "skips" all the non [A-Z] ([^A-Z]) by putting them in a non-capturing group. This is done 0-infinite times by the last *. Then a little LINQ to select the value of each capture .Select(p => p.Value) and the string.Join to join them.

    Note that this isn't Unicode friendly... ÀÈÌÒÙ will be ignored. A better regex would use @"(?:(\p{Lu}+)(?:[^\p{Lu}]*))*" where \p{Lu} is the Unicode category UppercaseLetter.

    (yes, this is useless... The other methods that use LINQ + IsUpper are better :-) but the whole example was built just to show the problems of Regexes with Unicode)

    MUCH EASIER:

    var ac = Regex.Replace("Alfa_BetaGameDelta_Epsilon", @"[^\p{Lu}]", string.Empty);
    

    simply remove all the non-uppercase letters :-)

提交回复
热议问题