How to: Strip Invalid Characters from a String

Microsoft Silverlight will reach end of support after October 2021. Learn more.

The following code example uses the static Regex.Replace method to strip invalid characters from a string. You can use the CleanInput method defined in this example to strip potentially harmful characters that have been entered into a text field in a form that accepts user input. In this case, CleanInput strips out all nonalphanumeric characters except periods (.), at symbols (@), and hyphens (-), and returns the remaining string. However, you can modify the regular expression pattern so that it strips out any characters that should not be included in an input.

Example

using System;
using System.Text.RegularExpressions;

public class Example
{
   static string CleanInput(string strIn)
   {
      // Replace invalid characters with empty strings.
      return Regex.Replace(strIn, @"[^\w\.@-]", "");
   }
}