试题要求:
从文本文件中搜索所有的qq号码。
考察知识点:
文件操作(I/O流)、正则表达式
参考答案:
/// <summary>
/// 从文本中搜索所有长度为5-11位的qq号码
/// </summary>
/// <param name="fileText">目标文本串</param>
private static void GetQQNumberListFromText(string fileText)
{
Regex regex = new Regex(@"\d{5,10}");
MatchCollection allResult = regex.Matches(fileText);
foreach (Match item in allResult)
{
Console.WriteLine(item.Value);
}
}
/// <summary>
/// 从文件中读取所有的文本字符信息
/// </summary>
/// <param name="filePath">文件名称</param>
/// <returns>文件内的文本</returns>
private static string GetTextFromFile(string filePath)
{
return File.ReadAllText(filePath);
}
static void Main(string[] args)
{
string filePath = Environment.CurrentDirectory;
DirectoryInfo directory = new DirectoryInfo(filePath);
filePath = directory.Parent.Parent.FullName;
filePath = Path.Combine(filePath, "qq.txt");
Console.WriteLine(filePath);
string fileText = GetTextFromFile(filePath);
GetQQNumberListFromText(fileText);
}