Replacing substrings using Regex in C# .NET: string cleaning example
July 14, 2017 Leave a comment
We often need to sanitize string inputs where the input value is out of our control. Some of those inputs can come with unwanted characters. The following method using Regex removes all non-alphanumeric characters except for ‘@’, ‘-‘ and ‘.’:
private static string RemoveNonAlphaNumericCharacters(String input) { return Regex.Replace(input, @"[^\w\.@-]", string.Empty); }
Calling this method like…
string cleanString = RemoveNonAlphaNumericCharacters("()h{e??l#'l>>o<<");
…returns “hello”.
View all posts related to string and text operations here.