Remove all non alphabetic chars from string in C#
To remove all non numeric characters from a string in C# we can use regex expression method Regex.Replace() and pass the string as first parameter and the expression[^.a-z-A-Z ]
as second parameter and ""
(empty string) as third parameter. Make sure you include the required namespace using System.Text.RegularExpressions;
Example
In below example we added to expression a white space so it keeps the space between hello and user words.using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string message = "hello 1 user";
string newString = Regex.Replace(message, "[^.a-z-A-Z ]", "");
Console.WriteLine(newString);
}
}
Output
hello user