Scott Chamberlain
Scott Chamberlain

Reputation: 127603

Regex pattern failing

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

Upvotes: 1

Views: 115

Answers (3)

Mike
Mike

Reputation: 6050

Try this

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

or

\W

Upvotes: 0

Mark Rushakoff
Mark Rushakoff

Reputation: 258478

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

Upvotes: 4

LukeH
LukeH

Reputation: 269628

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

Upvotes: 5

Related Questions