Removing Non-Alphanumeric Characters with Exceptions
When dealing with strings, it may be necessary to remove non-alphanumeric characters while preserving specific symbols like dashes and spaces. Here's how to achieve this in C#:
Solution:
To remove all non-alphanumeric characters except dashes and space characters from a string, utilize regular expressions to replace them with an empty string.
C# Code:
string str = "My-string123!"; Regex rgx = new Regex("[^a-zA-Z0-9 -]"); str = rgx.Replace(str, ""); Console.WriteLine(str); // Output: My-string123
Explanation:
The pattern [^a-zA-Z0-9 -] matches any character that is not an alphanumeric character (a-z, A-Z, 0-9) or a dash (-) or a space ( ). By replacing this pattern with an empty string, it effectively removes all non-alphanumeric characters.
The above is the detailed content of How to Remove Non-Alphanumeric Characters in C# While Keeping Dashes and Spaces?. For more information, please follow other related articles on the PHP Chinese website!