Parsing strings, extracting numbers and letters

What is the easiest way to parse a string and extract the number and letter? I have a string that can be in the following format (number | letter or letter | number), that is, "10A", "B5", "C10", "1G", etc.

I need to extract 2 parts, that is, "10A" → "10" and "A".

Update: Thank you all for the excellent answers.

+5
source share
6 answers

The easiest way is to use regular expressions.

((?<number>\d+)(?<letter>[a-zA-Z])|(?<letter>[a-zA-Z])(?<number>\d+))

Then you can match it with your string and extract the value from the groups.

Match match = regex.Match("10A");
string letter = match.Groups["letter"].Value;
int number = int.Parse(match.Groups["number"].Value);
+11
source

- . IsDigit, , , :

char letter = str[0];
int index = 1;
if (Char.IsDigit(letter)) {
   letter = str[str.Length - 1];
   index = 0;
}
int number = int.Parse(str.Substring(index, str.Length - 1));
+6
char letter = str.Single(c => char.IsLetter(c));
int num = int.Parse(new string(str.Where(c => char.IsDigit(c)).ToArray()));

( , "5A2" "A" "52" ), .

+4

:

string number = input.Trim("ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray());
string letter = input.Trim("0123456789".ToCharArray());
+3

. gc1 [ "letter" ], gc1 [ "number" ], gc2 [ "letter" ] gc2 [ "number" ] , , ( , ).

epxression , .

        Regex pattern = new Regex("^(?<letter>[a-zA-Z]+)(?<number>[0-9]+)|(?<number>[0-9]+)(?<letter>[a-zA-Z]+)$");
        string s1 = "12A";
        string s2 = "B45";
        Match m1 = pattern.Match(s1);
        Match m2 = pattern.Match(s2);
        GroupCollection gc1 = m1.Groups;
        GroupCollection gc2 = m2.Groups;
+1

Using Sprache and some Linq kung-fu:

var tagParser =
    from a in Parse.Number.Or(Parse.Letter.Once().Text())
    from b in Parse.Letter.Once().Text().Or(Parse.Number)
    select char.IsDigit(a[0]) ?
           new{Number=a, Letter=b} : new{Number=b, Letter=a};

var tag1 = tagParser.Parse("10A");
var tag2 = tagParser.Parse("A10");

tag1.Letter; // should be A 
tag1.Number; // should be 10

tag2.Letter; // should be A
tag2.Number; // should be 10

/* Output:
   A
   10
   A
   10
 */
0
source

All Articles