In this article, we will see how to Remove non-alphanumeric characters from a string in C#
1.
- Using Regular Expression
Code language: C# (cs)
private static void RemoveNoAlphaChar() { string str = "dotnetoffice16@gmail.com"; str = Regex.Replace(str, "[^a-zA-Z0-9]", String.Empty); Console.WriteLine(str); Console.ReadLine(); }
the output will be like below, which doesn't contain @ and .(dot)
dotnetoffice16gmailcom
2.. Using Array.FindAll() method
The Array.FindAll() method returns all elements of the specified
sequence which satisfy a certain condition. To filter only alphanumeric
characters, pass Char.IsLetterOrDigit to the FindAll()
method, as below:
Code language: C# (cs)private static void RemoveNoAlphaChar() { string str = "dotnetoffice16@gmail.com"; str = String.Concat(Array.FindAll(str.ToCharArray(), Char.IsLetterOrDigit)); Console.WriteLine(str); Console.ReadLine(); }
1.
3. Using LINQ
Another similar
solution uses LINQ’s Where() method to filter elements of a sequence based on a
condition.
Code language: C# (cs)private static void RemoveNoAlphaChar() { string str = "dotnetoffice16@gmail.com"; str = String.Concat(str.Where(char.IsLetterOrDigit)); Console.WriteLine(str); Console.ReadLine(); }
1. Output
EmoticonEmoticon