Darren Young
Darren Young

Reputation: 11090

C# Regex to return only the letters

I am having a few problems with regex in C#. I require a string to be passed in and only the letters to be returned (as a string), so for example if the string is "4hr", I want "hr" to be returned. If the string is "Gp. 23", I just want "Gp" to be returned.

I've tried:

 string[] extractedWords = System.Text.RegularExpressions.Regex.Split(expr, "[a-zA-Z]");

But that doesn't seem to work.

Upvotes: 0

Views: 381

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500225

If you want just a string to be returned, using split is a bad idea. How about:

string filtered = Regex.Replace(expr, "[^A-Za-z]", "");

In other words "replace anything that isn't A-Z or a-z with an empty string". Note that that will also strip non-ASCII letters; you may want to use a Unicode character class (e.g. "letter") instead.

Upvotes: 4

Related Questions