Using Regex.Replace

Say you want to get the username from a fully qualified username such as MyDomain\AUser

Most developers would turn to SubString and LastIndexOf functions .. for example

string userName = @"MyDomain\AUser";
string result = userName.SubString(userName.LastIndexOf(@"\"));

Instead of using these functions you should consider the use of Regex.Replace(). Here's how you'd do it:

string userName = @"MyDomain\AUser";
string result = Regex.Replace(userName, @".*\\(.*?)$""$1");

You can see from the example above that the Replace method is matching on the string and just returning the first Group. (.*?) is represented in the replace expression by $1

As I'm sure you can imagine, the possibilities here are endless... example

string userName = @"MyDomain\AUser";
string result = Regex.Replace(userName, @".*\\(.*?)$""Welcome back $1. Nice to see you again");

I hope you find uses for Regex.Replace in your applications.

Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo ( and is also the creator of GeekZilla.

Add Comment


Your comment has been received and will be shown once it passes moderation.