Is there a robust way to parse the username and domain from a string?

1.8k views Asked by At

I search for a robust way to parse a string into username and domain. The following strings are valid (as specified in the user name formats):

  • domain\username
  • username
  • username@domain

Note that my application has to run offline and can't validate against any service.

Edit: I'm looking for a class in the .NET Framework that takes my string to construct a user object that I can use to get the domain and username in the same way like System.Uri will parse a url for me.

2

There are 2 answers

0
ChrisK On

You could obviously use a RegEx like

([a-zA-Z_\-0-9]+)[\\@]{0,1}([a-zA-Z_\-0-9]+){0,1}

Only a sample RegEx, will not work on Domains with .com or similar endings.

to get the username and a domain, if one exists. I personally find functions with regular expression hard to support and manage, because of their cryptic notation. If you are limited to 3 notations, I'd say you should implement a function that parses every one of the three notations.

4
jasonnissen On

Something like the following should work.

static string ParseUserName(string logonName)
{
    if (logonName.Contains('\\'))
    {
        var logonNameParts = logonName.Split('\\');
        return logonNameParts[1];
    }

    if (logonName.Contains('@'))
    {
        var logonNameParts = logonName.Split('@');
        return logonNameParts[0];
    }

    return logonName;
}