ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Strip

Strips unwanted characters on the specified string.

Source

using System.Text.RegularExpression;

public static class StringEx
{
	/// <summary>
	/// Strip unwanted characters and replace them with empty string
	/// </summary>
	/// <param name="data">the string to strip characters from.</param>
	/// <param name="textToStrip">Characters to strip. Can contain Regular expressions</param>
	/// <returns>The stripped text if there are matching string.</returns>
	/// <remarks>If error occurred, original text will be the output.</remarks>
	public static string Strip(this string data, string textToStrip)
	{
		var stripText = data;

		if (string.IsNullOrEmpty(data)) return stripText;

		try
		{
			stripText = Regex.Replace(data, textToStrip, string.Empty);
		}
		catch
		{
		}
		return stripText;
	}

	/// <summary>
	/// Strips unwanted characters on the specified string
	/// </summary>
	/// <param name="data">the string to strip characters from.</param>
	/// <param name="textToStrip">Characters to strip. Can contain Regular expressions</param>
	/// <param name="textToReplace">the characters to replace the stripped text</param>
	/// <returns>The stripped text if there are matching string.</returns>
	/// <remarks>If error occurred, original text will be the output.</remarks>
	public static string Strip(this string data, string textToStrip, string textToReplace)
	{
		var stripText = data;

		if (string.IsNullOrEmpty(data)) return stripText;

		try
		{
			stripText = Regex.Replace(data, textToStrip, textToReplace);
		}
		catch
		{
		}
		return stripText;
	}
}

Example

string testString = "alpha129";
Console.WriteLine("Numeric Only: " + testString.Strip(@"[\D]"); // returns 129
Console.WriteLine("Alphabet Only: " + testString.Strip(@"[\d]"); // returns alpha

Author: Earljon Hidalgo

Submitted on: 16 mei 2008

Language: C#

Type: System.String

Views: 6442