将以上代码修改成符合C#
时间: 2023-11-09 13:04:30 浏览: 41
以下是将代码修改为符合 C# 语言的示例:
```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
public class UserInfo
{
public string Name { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
public class Program
{
public static UserInfo ExtractUserInfo(string filePath)
{
string content = File.ReadAllText(filePath);
List<string> nameMatches = new List<string>(Regex.Matches(content, @"姓名:([\w\s]+)"));
List<string> ageMatches = new List<string>(Regex.Matches(content, @"年龄:(\d+)"));
List<string> genderMatches = new List<string>(Regex.Matches(content, @"性别:([\w\s]+)"));
List<string> phoneMatches = new List<string>(Regex.Matches(content, @"电话:(\d+)"));
List<string> emailMatches = new List<string>(Regex.Matches(content, @"邮箱:([\w\.]+@[\w\.]+)"));
string name = (nameMatches.Count > 0) ? nameMatches[0] : null;
string age = (ageMatches.Count > 0) ? ageMatches[0] : null;
string gender = (genderMatches.Count > 0) ? genderMatches[0] : null;
string phone = (phoneMatches.Count > 0) ? phoneMatches[0] : null;
string email = (emailMatches.Count > 0) ? emailMatches[0] : null;
UserInfo userInfo = new UserInfo
{
Name = name,
Age = age,
Gender = gender,
Phone = phone,
Email = email
};
return userInfo;
}
public static void Main(string[] args)
{
string filePath = "path/to/your/txt/file.txt";
UserInfo userInfo = ExtractUserInfo(filePath);
Console.WriteLine(userInfo.Name);
Console.WriteLine(userInfo.Age);
Console.WriteLine(userInfo.Gender);
Console.WriteLine(userInfo.Phone);
Console.WriteLine(userInfo.Email);
}
}
```
上述代码使用了 C# 的语法和类来实现相同的功能。通过使用 `Regex.Matches` 方法可以提取出所有匹配结果,然后根据需要选择第一个匹配结果或者其他处理方式。最后,将提取得到的属性值赋值给 `UserInfo` 类的属性,并进行打印输出。请确保将 `filePath` 替换为实际的文件路径。