You are not Logged in
Would you like to Login or Register

Today is: Friday, 21 November, 2008
Check this months hot topics

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.

kick it on DotNetKicks.com del.icio.us digg Mister Wong YahooMyWeb Reddit Furl Spurl blogmarks
Paul Hayman Skype
Author : Paul Hayman
Published : Friday, 04 August, 2006

Paul is the COO of kwiboo ltd consultant and has more than a decade of 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 (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Add Comment

Enter your comment below and it will be submitted for moderation.

Your Name

Add Tag

Please enter tags for this article, seperated by semi-colon ;

View Tag's by : # articles | # views