Problem
How can I remove all non-alphanumeric characters except dashes and spaces from a string?
Asked by Luke101
Solution #1
Replace [^a-zA-Z0-9 -] with an empty string.
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
Answered by Amarghosh
Solution #2
I could have used RegEx; they can be a beautiful solution, but they can also be inefficient. Here’s one possibility.
char[] arr = str.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
|| char.IsWhiteSpace(c)
|| c == '-')));
str = new string(arr);
When working with the compact framework (which lacks FindAll),
Replace FindAll with1
char[] arr = str.Where(c => (char.IsLetterOrDigit(c) ||
char.IsWhiteSpace(c) ||
c == '-')).ToArray();
str = new string(arr);
ShawnFeatherly has one comment.
Answered by ata
Solution #3
You can try:
string s1 = Regex.Replace(s, "[^A-Za-z0-9 -]", "");
Where s denotes the length of your string.
Answered by josephj1989
Solution #4
Using System.Linq
string withOutSpecialCharacters = new string(stringWithSpecialCharacters.Where(c =>char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-').ToArray());
Answered by Zain Ali
Solution #5
[ws-]* [ws-]* [ws-]* [ws-]* [ws-]* [ws-]
Because there can be a tab in the text, s is preferable to space ().
Answered by True Soft
Post is based on https://stackoverflow.com/questions/3210393/how-do-i-remove-all-non-alphanumeric-characters-from-a-string-except-dash