Remove Non-Alphanumeric Characters from a String

A colleague was looking for an easy way to remove all non-alphanumeric characters from a string and it took some time to find the easiest way was to use RegEx.Replace() as follows:

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

while /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 alternative if you don’t want to allow the underscore you can use [^a-zA-Z0-9].

The following regular expression quick reference helped in finding this solution:
Regular Expressions Quick Reference

~ by mundeep on March 7, 2008.

Leave a Reply

You must be logged in to post a comment.