remove special characters from text in csharp

One way to remove special characters from a string in C# is to use regular expressions.

Here is an example code snippet that replaces any non-word character (i.e. any character that is not a letter, digit, or underscore) with an empty string:

main.cs
using System.Text.RegularExpressions;

string input = "This is some input with!@#$special^&*characters";
string output = Regex.Replace(input, @"\W", "");

Console.WriteLine(output); // Output: "Thisissomeinputwithspecialcharacters"
232 chars
7 lines

The Regex.Replace method takes two parameters: the input string and a regular expression pattern. In this case, the pattern \W matches any non-word character.

We wrap this in a method for future reuse:

main.cs
using System.Text.RegularExpressions;

public string RemoveSpecialCharacters(string input)
{
    return Regex.Replace(input, @"\W", "");
}

string input = "This is some input with!@#$special^&*characters";
string output = RemoveSpecialCharacters(input);

Console.WriteLine(output); // Output: "Thisissomeinputwithspecialcharacters"
332 chars
12 lines

related categories

gistlibby LogSnag