String parsing, extracting numbers and letters

后端 未结 6 2081
逝去的感伤
逝去的感伤 2020-12-30 15:19

What\'s the easiest way to parse a string and extract a number and a letter? I have string that can be in the following format (number|letter or letter|number), i.e \"10A\",

6条回答
  •  [愿得一人]
    2020-12-30 15:55

    Here is how I would approach this. You can step through this and put gc1["letter"], gc1["number"], gc2["letter"], and gc2["number"] in the watch window to see that it worked (step just past the last line of code here, of course).

    The regular epxression will take either pattern requiring one or more letter and number in each case.

            Regex pattern = new Regex("^(?[a-zA-Z]+)(?[0-9]+)|(?[0-9]+)(?[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;
    

提交回复
热议问题