tags:

views:

65

answers:

3

I am trying to strip out all things that are in a string that are not a letter number or space so I created the regex

private static Regex _NonAlphaChars = new Regex("[^[A-Za-z0-9 ]]", RegexOptions.Compiled);

however When I call _NonAlphaChars.Replace("Scott,", ""); it returns "Scott,"

What am I doing wrong that it is not matching the ,?

+5  A: 
private static Regex _NonAlphaChars =
    new Regex("[^A-Za-z0-9 ]", RegexOptions.Compiled);
LukeH
+4  A: 

You did something funny with the double bracketing. Change it to just

[^A-Za-z0-9 ]

Dropping your original expression into The Regex Coach explained your regex as:

The regular expression is a sequence consisting of the expression '[[^A-Za-z0-9 ]' and the character ']'.

For contrast, the explanation of the alternative I wrote is:

The regular expression is a character class representing everything but the range of characters from the character 'A' to the character 'Z', the range of characters from the character 'a' to the character 'z', the range of characters from the character '0' to the character '9', and the character ' '.

Mark Rushakoff
Thanks for the link to The Regex Coach! I always have just been trying to do research on www.regular-expressions.info to figure out my expressions.
Scott Chamberlain
A: 

Try this

[^A-Za-z0-9\s]

or

\W

Mike