user1 user1 - 1 year ago 67
C# Question

How do I get the first group of alpha characters from string?

If I have a string how do I extract the first alpha characters from the string such that I end up with the starting alpha characters or an empty string. E.g:

AB12 9HG => "AB"
PJ11 => "PJ"
123JO => ""

Is this possible with regex or is there an easier way?

Answer Source

You can use LINQ to build the result:

new String(s.TakeWhile(p => Char.IsLetter(p)).ToArray());

Basically, just take the characters from the start until the first non-alpha char.

If there is leading whitespace, Trim() the string first.