GurdeepS
GurdeepS

Reputation: 67213

Remove numbers and characters only from string

Given a string containing numbers and characters eg

Mi2ch£al

What would be the relevant regex to remove everything but letters (therefore numbers and characters)?

Also, I am using .NET 2.0 for this task.

Upvotes: 0

Views: 665

Answers (4)

drf
drf

Reputation: 8699

\p{L} matches any character that is a letter, and \P{L} any character that is not a letter (including non-Latin character sets, accented characters, etc.). Thus, you could simply use:

Regex.Replace(input, @"\P{L}", String.Empty)

where input is the input string.

Upvotes: 0

HatSoft
HatSoft

Reputation: 11191

If you dont mind using Linq :

string s = new string("Mi2ch£al".Where(c => !char.IsNumber(c) && !char.IsLetter(c)).ToArray());

Upvotes: 2

burning_LEGION
burning_LEGION

Reputation: 13450

replace regex [^a-zA-Z] with empty string or [^a-zA-Z\s] it's save spaces

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

string s = "Mi2ch£al";
s = Regex.Replace(s, @"[^\w\s]", "");

and if you don't want international accented characters:

string s = "Mi2ch£al";
s = Regex.Replace(s, @"[^a-zA-Z0-9\s]", "");

Upvotes: 0

Related Questions