DotNetDeveloper
DotNetDeveloper

Reputation: 587

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

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";

Upvotes: 11

Views: 63998

Answers (3)

Mahesh Gotakhinde
Mahesh Gotakhinde

Reputation: 1

Here is Java code to replace special characters

String inputString = "1/10 EP Sp'arrowha?wk XT R;TR 2.4GHz R\\ed";
String re = "[;\\\\/:*?\"<>|&']";
Pattern pattern = Pattern.compile(re);
Matcher matcher = pattern.matcher(inputString);
String outputString = matcher.replaceAll(" ");

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359776

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/

Upvotes: 24

ic3b3rg
ic3b3rg

Reputation: 14927

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

Upvotes: 4

Related Questions