1

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 ,?

1
  • The problem is that you can't nest character classes like that. So that regex you have actually gets parsed as: any character in the negated set [^[A-Za-z0-9 ] (where the second [ is actually part of the class) followed by a single ] Commented Jun 11, 2010 at 16:51

3 Answers 3

5
private static Regex _NonAlphaChars =
    new Regex("[^A-Za-z0-9 ]", RegexOptions.Compiled);
Sign up to request clarification or add additional context in comments.

Comments

4

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 ' '.

1 Comment

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.
0

Try this

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

or

\W

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.