MST
星途 面试题库

面试题:C#字符串复杂处理与正则表达式分组应用

给定字符串`string data = "Name: John, Age: 30, Email: john@example.com; Name: Jane, Age: 25, Email: jane@example.com"`,要求使用C#和正则表达式完成以下操作:1. 提取每个人的姓名、年龄和邮箱,存储到一个自定义的`Person`类的列表中,`Person`类包含`Name`(字符串)、`Age`(整数)、`Email`(字符串)属性。2. 验证提取的邮箱格式是否正确,如果不正确则在控制台输出错误信息。
32.1万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

class Program
{
    static void Main()
    {
        string data = "Name: John, Age: 30, Email: john@example.com; Name: Jane, Age: 25, Email: jane@example.com";
        List<Person> people = new List<Person>();

        string pattern = @"Name: (\w+), Age: (\d+), Email: (\S+)";
        MatchCollection matches = Regex.Matches(data, pattern);

        foreach (Match match in matches)
        {
            Person person = new Person
            {
                Name = match.Groups[1].Value,
                Age = int.Parse(match.Groups[2].Value),
                Email = match.Groups[3].Value
            };

            if (!IsValidEmail(person.Email))
            {
                Console.WriteLine($"Invalid email for {person.Name}: {person.Email}");
            }
            else
            {
                people.Add(person);
            }
        }

        // 可以在这里对people列表进行进一步操作
    }

    static bool IsValidEmail(string email)
    {
        string emailPattern = @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
        return Regex.IsMatch(email, emailPattern);
    }
}