我正在编写这个小程序来从文本文件中提取任意数量的电子邮件地址。我收到两个错误,“使用未分配的局部变量。”我不确定为什么。
static void Main(string[] args)
{
string InputPath = @"C:\Temp\excel.txt";
string OutputPath = @"C:\Temp\emails.txt";
string EmailRegex = @"^(?:[a-zA-Z0-9_'^&/+-])+(?:\.(?:[a-zA-Z0-9_'^&/+-])+)*@(?:(?:\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\.){3}(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\]?)|(?:[a-zA-Z0-9-]+\.)+(?:[a-zA-Z]){2,}\.?)$";
string Text = String.Empty;
StringBuilder Output;
List<string> Emails;
using (TextReader tr = new StreamReader(InputPath))
{
Text = tr.ReadToEnd();
}
MatchCollection Matches = Regex.Matches(Text,EmailRegex);
foreach (Match m in Matches)
{
Emails.Add(m.ToString().Trim()); // one error is here
}
foreach (String s in Emails)
{
Output.Append(s + ","); // the other error is here
}
using (TextWriter tw = new StreamWriter(OutputPath))
{
tw.Write(Output.ToString());
}
}
抱歉格式化...我有点时间紧迫!
编辑:哇。我是个白痴 - 一定是因为我时间紧迫!!!!
最佳答案
您没有初始化 StringBuilder 和 List。
StringBuilder Output = new StringBuilder();
List<string> Emails = new List<String>();
关于c# - 帮助解决简单的 C# 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1143147/