Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# regular expression to strip all but alphabetical and numerical characters from a string?

Tags:

c#

regex

I've been scratching my head trying to figure out how to use Regex.Replace to take an arbitrary string and return a string that consists of only the alpha-numeric characters of the original string (all white space and punctuation removed).

Any ideas?

like image 208
Pete Alvin Avatar asked Jul 07 '10 21:07

Pete Alvin


2 Answers

var result = Regex.Replace(input, @"[^a-zA-Z0-9]", "");
like image 92
František Žiačik Avatar answered Oct 05 '22 22:10

František Žiačik


You could use linq:

string alphanumeric = new String(original.Where(c => Char.IsLetterOrDigit(c)).ToArray());
like image 34
Lee Avatar answered Oct 05 '22 22:10

Lee