C # regex to remove all strings except alphanumeric characters from string?

I scratched my head, trying to figure out how to use Regex.Replace to take an arbitrary string and return a string consisting only of the alphanumeric characters of the original string (all spaces and punctuation removed).

Any ideas?

+5
source share
2 answers
var result = Regex.Replace(input, @"[^a-zA-Z0-9]", "");
+11
source

You can use linq:

string alphanumeric = new String(original.Where(c => Char.IsLetterOrDigit(c)).ToArray());
+5
source

All Articles