Removing Non-Alphanumeric Characters with Exception for Hyphens and Spaces
Need help removing all non-alphanumeric characters from a string, but want to keep hyphens and spaces? Here's how to achieve it:
Solution:
To achieve this, use a regular expression to replace all non-alphanumeric characters, other than hyphens and spaces, with an empty string. Here's the code snippet:
Regex rgx = new Regex("[^a-zA-Z0-9 -]"); str = rgx.Replace(str, "");
This regex pattern [^a-zA-Z0-9 -] includes a negation character (^) to indicate that any character that matches the pattern should be excluded. Within the pattern, [a-zA-Z0-9 -] matches all letters, numbers, spaces, and hyphens, so the negation [^a-zA-Z0-9 -] will match all characters that are not alphanumeric or hyphen/space characters.
By using rgx.Replace(str, ""), you replace all occurrences of non-alphanumeric characters with an empty string, effectively removing them from your string while maintaining hyphens and spaces.
The above is the detailed content of How to Remove Non-Alphanumeric Characters Except Hyphens and Spaces from a String?. For more information, please follow other related articles on the PHP Chinese website!