Pete Alvin
Pete Alvin

Reputation: 4800

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

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?

Upvotes: 5

Views: 1656

Answers (2)

František Žiačik
František Žiačik

Reputation: 7614

var result = Regex.Replace(input, @"[^a-zA-Z0-9]", "");

Upvotes: 11

Lee
Lee

Reputation: 144206

You could use linq:

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

Upvotes: 5

Related Questions