如何对数字和单词进行分组?

时间:2019-04-03 13:29:53

标签: c# .net

string str = "We have 23 students at Cybernetics, 32 students at Computer Science and we also have 12 teachers";

我需要从字符串中提取学生和老师的人数。 将会有一个关键字列表,我需要为它们计算总数。

string input = "We have 23 students at Cybernetics, 32 students at Computer Science and we also have 12 teachers";

        List<string> keywords = new List<string>();
        keywords.Add("teacher");
        keywords.Add("student");
        keywords.Add("kid");
        keywords.Add("parent");

        foreach(var k in keywords)
        {
            if (input.Contains(k))
            {
                ????
            }
        }
  

产出:55名学生,12名老师。

2 个答案:

答案 0 :(得分:1)

这里是一个不带正则表达式的示例,您可以对其进行修改以支持教师,父母,……:

    string input = "We have 23 students at Cybernetics, 32 students at Computer Science and we also have 12 teachers";
    var words = input.Split(' ');
    int studentCount = 0;
    for(int i=0; i<words.Length; i++)
    {
        string word = words[i];
        int nr;
        if(int.TryParse(word, out nr))
        {
            if(i+1 < words.Length && words[i+1] == "students") studentCount+=nr;
        }
    }
    Console.WriteLine("Students " + studentCount);

链接:https://dotnetfiddle.net/jMzPr9

答案 1 :(得分:0)

这是完整的Regex解决方案

string input = @"We have 23 students at Cybernetics, 32 students at Computer Science and we also have 12 teachers";

List<string> keywords = new List<string>();
keywords.Add("student");
keywords.Add("teacher");
keywords.Add("kid");
keywords.Add("parent");

foreach(var k in keywords)
{
    string pattern = @"(\d*) "+k;
    MatchCollection matches = Regex.Matches(input, pattern);
    int total = 0;
    foreach (Match match in matches) {
        total+= Convert.ToInt32(match.Groups[1].Value);
    }
    Console.WriteLine(total + " " + k+", ");
}