How to remove all non alphanumeric characters from a string except dash and space characters.
+13
A:
Replace [^a-zA-Z0-9 -]
with an empty string.
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
Amarghosh
2010-07-09 06:50:27
Worth mentioning that `-` must be at the end of the character class, or escaped with a backslash, to prevent being used for a range.
Peter Boughton
2010-07-09 09:18:50
I am using classic ASP (not C# as the original question is tagged) - if I enter: 50025454$ this works fine but if I enter 50025454$$ this fails. (I need to add + to the regex). Is this the same in C#?
Dan
2010-09-21 15:20:41
That said - using Regex rgx = new Regex("[^a-zA-Z0-9 -]+") and trying 5002$5454$ still fails.
Dan
2010-09-21 15:22:07
@Dan set the global flag in your regex - without that, it just replaces the first match. A quick google should tell you how to set global flag in classic ASP regex. Otherwise, look for a `replaceAll` function instead of `replace`.
Amarghosh
2010-09-22 03:49:32
A:
The regex is [^\w\s\-]*
:
\s
is better to use instead of space (), because there might be a tab in the text.
True Soft
2010-07-09 06:55:25
...and newlines, and all other characters considered "whitespace".
Peter Boughton
2010-07-09 09:17:08
+1
A:
TRY
string s1= Regex.Replace(s,"[^A-Za-z0-9 _]","");
WHERE s is your string
josephj1989
2010-07-09 06:55:36
+4
A:
I could have used RegEx, they can provide elegant solution but they can cause performane issues. Here is one solution
char[] arr = str.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-')));
str = new string(arr);
cornerback84
2010-07-09 07:00:07
A:
String stringToEdit = "string to replace characters in!!!!";
Regex regex = new Regex("[^a-zA-Z0-9 -]");
stringToEdit = regex.Replace(stringToEdit, String.Empty);
simonalexander2005
2010-07-09 08:35:47