Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx to replace special characters in a string with space ? asp.net c#

Tags:

c#

regex

asp.net

string inputString = "1/10 EP Sp'arrowha?wk XT R;TR 2.4GHz Red";
//Characters Collection: (';', '\', '/', ':', '*', '?', ' " ', '<', '>', '|', '&', ''')
string outputString = "1 10 EP Sp arrowha wk XT R TR 2.4GHz Red";
like image 530
DotNetDeveloper Avatar asked May 18 '11 18:05

DotNetDeveloper


2 Answers

Full disclosure regarding the following code:

  • It's not tested
  • I probably messed up the character escaping in new Regex(...);
  • I don't actually know C#, but I can Google for "C# string replace regex" and land on MSDN

    Regex re = new Regex("[;\\/:*?\"<>|&']");
    string outputString = re.Replace(inputString, " ");
    

Here's the correct code:

string inputString = "1/10 EP Sp'arrowha?wk XT R;TR 2.4GHz R\\ed";
Regex re = new Regex("[;\\\\/:*?\"<>|&']");
string outputString = re.Replace(inputString, " ");
// outputString is "1 10 EP Sp arrowha wk XT R TR 2.4GHz R ed"

Demo: http://ideone.com/hrKdJ

Also: http://www.regular-expressions.info/

like image 56
Matt Ball Avatar answered Nov 15 '22 08:11

Matt Ball


string outputString = Regex.Replace(inputString,"[;\/:*?""<>|&']",String.Empty)
like image 43
ic3b3rg Avatar answered Nov 15 '22 06:11

ic3b3rg