【问题标题】:How to read from file and convert this specific file text into a <string, string> dictionary如何从文件中读取并将此特定文件文本转换为 <string, string> 字典
【发布时间】:2021-07-25 18:15:03
【问题描述】:

我想从 .txt 文件中读取并将文本转换为 字典。不过,我只想存储 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}]

【问题讨论】:

  • 到目前为止,您自己尝试过什么?你遇到了什么问题?你研究了什么?
  • 我了解如何根据 X 和 Y 值之间末尾的逗号值拆分文本,但我不明白如何处理所有其余文本/如何处理{X=,Y=} 之前的所有内容。例如,一个 File 对象将是完美的,但我只是不明白如何为这个特定的用例实现它。如果它是更简单的格式并且只有 X 和 Y 值,这对我的大脑来说会更容易。 @FranzGleichmann

标签: c# file dictionary io windows-forms-designer


【解决方案1】:

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

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;
}

【讨论】:

  • 感谢您的回答;它完美无缺! Reg Ex 是我一直在努力解决的问题,这是一个非常清晰易懂的解释。感谢您的宝贵时间。
猜你喜欢
  • 2021-03-25
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
  • 1970-01-01
相关资源
最近更新 更多