Friday, June 22, 2012

Remove special characters from a string using Regular Expression

If you're looking for an efficient way to remove special characters from a string, here is some sample code that utilizes a Regular Expression to do so:

using System.Text.RegularExpressions;
...
string inputString = "Sherman's Test #123";
string cleanOutputString = Regex.Replace(inputString,  @"[^A-Za-z0-9-_]", "");

This code sample will remove all characters except for alpha-numeric characters and "_".  If you would like to keep the empty characters/blank spaces, use this line instead:
string cleanOutputString = Regex.Replace(inputString,  @"[^A-Za-z0-9-_ ]", "");

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.