我一直在#574行得到“索引超出数组范围”的错误:
label.Font = new Font(fontNameFields [0],Single.Parse(fontNameFields [1]));
...我正在解析的以下文本文件包含以下确切信息:
Label
"hi tyler"
23, 76
Arial,12.5
...我可以成功解析所有其他信息(只是不是最后一行),我的代码是:
MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+), (\d+)");
foreach (Match match in lines)
{
string control = match.Groups[1].Value;
string text = match.Groups[2].Value;
int x = Int32.Parse(match.Groups[3].Value);
int y = Int32.Parse(match.Groups[4].Value);
String cfont = match.Groups[5].Value;
string color = match.Groups[6].Value;
Console.WriteLine("{0}, \"{1}\", {2}, {3}, {4}, {5}", control, text, x, y, cfont, color);
switch (control)
{
case "Label":
Label label = new Label();
label.Text = text;
label.AutoSize = true;
label.IsAccessible = true;
label.MouseClick += new MouseEventHandler(label_MouseClick);
label.MouseDoubleClick += new MouseEventHandler(label_MouseDoubleClick);
label.MouseDown += new MouseEventHandler(label_MouseDown);
label.MouseMove += new MouseEventHandler(label_MouseMove);
label.MouseUp += new MouseEventHandler(label_MouseUp);
label.Location = new Point(x, y);
canvas.Controls.Add(label);
String fontName = cfont;
String[] fontNameFields = fontName.Split(',');
label.Font = new Font(fontNameFields[0], Single.Parse(fontNameFields[1]));
...我认为正则表达式中可能存在一些错误,它会获得字体...我不知道,但它只是不起作用,有人可以帮忙吗?
有关此问题的历史记录,请参阅:Parsing font info and converting it to System.Drawing.Font
答案 0 :(得分:0)
尝试
@"(.+?)\r\n""([^""]+)""\r\n(\d+), (\d+)\r\n(\w+,\d+\.?\d)"
它类似于slashmais解决方案,在字体及其大小方面只有一点限制性,并且更接近你原来的,我喜欢它,因为块更清晰可见。