Saturday, April 11, 2009

How to remove trailing & leading spaces with regular expression in c#

The following code sample helps to remove trailing & leading spaces with regular expression in c#
This Needs a reference to System.Text.RegularExpressions. Pass the method, your string and it will trim the string

//Namespace Reference
using System.Text.RegularExpressions;

public string TrimString(string str) //pass the str which has to be trimmed
{
try
{
string pattern = @"^[ \t]+|[ \t]+$";
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
str = reg.Replace(str, "");
return str;
}
catch (Exception ex)
{
throw ex;
}
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home