简体   繁体   中英

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.

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 AZ or az with an empty string". Note that that will also strip non-ASCII letters; you may want to use a Unicode character class (eg "letter") instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM