tags:

views:

177

answers:

5

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
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
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
That said - using Regex rgx = new Regex("[^a-zA-Z0-9 -]+") and trying 5002$5454$ still fails.
Dan
@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
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
unless you want to remove tabs.
Matt Ellen
...and newlines, and all other characters considered "whitespace".
Peter Boughton
+1  A: 

TRY

   string s1= Regex.Replace(s,"[^A-Za-z0-9 _]","");

WHERE s is your string

josephj1989
+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
A: 
String stringToEdit = "string to replace characters in!!!!";
Regex regex = new Regex("[^a-zA-Z0-9 -]");
stringToEdit  = regex.Replace(stringToEdit, String.Empty);
simonalexander2005