This post will discuss how to remove non-alphanumeric characters from a string in C#.

If we’re to remove all non-alphanumeric characters from a string, we have to create a new string instance since strings are immutable in C#. This post provides an overview of several methods to accomplish this:

1. Using Regular Expression

The idea is to check for non-alphanumeric characters in a string and replace them with an empty string. We can use the regular expression [^a-zA-Z0-9] to identify non-alphanumeric characters in a string. Replace the regular expression [^a-zA-Z0-9] with [^a-zA-Z0-9 _] to allow spaces and underscore character.

Download  Run Code

 
If the regular expression is frequently called, you might want to pre-compile the regular expression for a faster search on the cost of increased startup time.

Download  Run Code

 
In ASCII, word characters are [a-zA-Z0-9_]. The regular expression \w and \W check for the word and non-word characters, respectively. Therefore, we can use regular expression [^\w]* or [\W]* to identify non-alphanumeric characters in a string.

Download  Run Code

2. Using Array.FindAll() method

The Array.FindAll() method returns all elements of the specified sequence which satisfies a certain condition. To filter only alphanumeric characters, pass Char.IsLetterOrDigit to the FindAll() method, as demonstrated below:

Download  Run Code

 
Note that the IsLetterOrDigit() method does not strictly check for ASCII characters in range A-Z, a-z, and 0-9. We can write our custom logic to check characters in the desired range, as shown below:

Download  Run Code

3. Using LINQ

Another similar solution uses LINQ’s Where() method to filter elements of a sequence based on a condition. We can use this as follows:

Download  Run Code

That’s all about removing all non-alphanumeric characters from a string in C#.