Quote for the Week

"Learn to enjoy every moment of your life"

Thursday, October 30, 2014

Remove special characters using Regular expression

This post will help you to remove the special characters in the given string. Using Regular expression we can achieve this. Here i'm replacing the special characters with empty character.

For using Regular Expression class, you have to import System.Text.RegularExpressions.
Here i have made a string which contains all the special characters. This is the input.
And the output will be the string, free of special characters.

using System.Text.RegularExpressions;

public void RemoveSpecialCharacter()
{
  string inputStr = "'he*s .anf{# & 54= Sp'a(bfda+.%fgf},gh_gh&? XT R;SD<kb<$)-fd!z*>~`5+7fdR\\^ed";
  Regex re = new Regex("[;\\\\/:*?\"<>|{}~`().,_!+=&%^@#$'-]");
  string outputStr = re.Replace(inputStr, " ");
  Response.Write("<b>Origional String:</b>"+inputStr + "<br/><br/>");
  Response.Write("<b>After Removed Special characters:</b>" + outputStr);
}


Output :

No comments: