字典,c#,file,dictionary,io,windows-forms-designer"/>

首页 > 解决方案 > 如何从文件中读取并将此特定文件文本转换为字典

问题描述

我想从 .txt 文件中读取并将文本转换为 <string, string> 字典。不过,我只想存储 X 和 Y 值,例如 <X, Y>。

我如何使用下面的当前文本文件来解决这个问题?

[System.Windows.Forms.PictureBox, SizeMode: Normal {X=359,Y=154}]
[System.Windows.Forms.PictureBox, SizeMode: Normal {X=678,Y=230}]
[System.Windows.Forms.PictureBox, SizeMode: Normal {X=625,Y=171}]
[System.Windows.Forms.PictureBox, SizeMode: Normal {X=565,Y=314}]
[System.Windows.Forms.PictureBox, SizeMode: Normal {X=409,Y=262}]
[System.Windows.Forms.PictureBox, SizeMode: Normal {X=410,Y=59}]
[System.Windows.Forms.PictureBox, SizeMode: Normal {X=777,Y=151}]

标签: c#filedictionaryiowindows-forms-designer

解决方案


一种方法是使用正则表达式:

var s = "[System.Windows.Forms.PictureBox, SizeMode: Normal {X=359,Y=154}]";

var reg = new Regex(pattern: "{X=([0-9]*),Y=([0-9]*)}");

var match = reg.Match(s);
if(match.Success)
{
    var x = match.Groups[1].Value; // string "359" but you can use int.TrypParse to get a number
    var y = match.Groups[2].Value;
}

推荐阅读