Using regular expressions to get initials from a string in C#

Here is a really simple string extension to help you get initials from a string in C#

    public static string ToInitials(this string str)
    {
      return Regex.Replace(str, @"^(?'b'w)w*,s*(?'a'w)w*$|^(?'a'w)w*s*(?'b'w)w*$", "${a}${b}", RegexOptions.Singleline)
    }

Here’s a breakdown on what the expression is doing:

  • ^ matches beginning of the string
  • (?‘b’w) captures first character of a word and stores in in ‘b’
  • w* matches the rest of the name
  • , matches a comma
  • s* matches > 0 spaces
  • (?’a’w)w* matches the second part of the name capturing the first letter into ‘b’
  • $ matches end of string
  • | or the alternate pattern w ithout the ,
  • Notice the ‘a’ and ‘b’ are swapped

There are more handy string extensions on ’String Extension Collection for C#

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.