Saturday, April 11, 2009

Remove Trailing Zeroes From a String in C# using Regular Expressions

The code sample is that of a function RemoveTrailingZeros in C#, that takes a string input and removes all trailing zeros in it.

The code uses the Regex object provided by the .Net class library. Regular Expressions optimize the operation of "searching patterns" in a string. The following code can also be taken as an example to remove any character (trailing) from a string. The only change require will be that we need to change the Regular Expression.


//Regex is in System.Text.RegularExpressions namespace
public string RemoveTrailingZeroes(string input)
{
Regex reg1 = new Regex("\\.\\d*(?<1>0+)[^\\d]*$", RegexOptions.IgnoreCase);

Match m = reg1.Match(input);
if( m.Success )
{
input = input.Replace(m.Groups["1"].Value, "");
Regex reg2 = new Regex("(?<1>\\.)[^\\d]*$", RegexOptions.IgnoreCase);
m = reg2.Match(input);

if( m.Success )
{
input = input.Replace(".", "" );
}
Regex reg3 = new Regex("\\d", RegexOptions.IgnoreCase );
m = reg3.Match(input);
if( !m.Success )
{
input = "0" + input;

}

}
if(input.StartsWith("."))
input = "0" + input;

return input;
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home