15 Sep 2011

Remove Non-Alphanumeric Characters from a String

 

newString = Regex.Replace(stringToCleanUp, @"[\W]", "");

Above is equal to :

newString = Regex.Replace(stringToCleanUp, @"[^a-zA-Z0-9]", "");

 

\w (lowercase) matches any ‘word’ character, equivalent to [a-zA-Z0-9_]
\W matches any ‘non-word’ character, ie. anything NOT matched by \w

As an alternate, if you don’t want to allow the underscore you can use [^a-zA-Z0-9]

No comments:

Post a Comment