我有一个包含竖线分隔格式内容的文件。这是在 WinForm 应用程序中的 C# 中。
完美格式示例:
1000|2014|01|AP|1|00000001|00
- 第一个值的长度应始终为 4。
- 第二个值 - 4 长度。
- 第三个值 - 2 个长度。
- 第 4 个值 - 2 个长度。
- 第 5 个值 - 1 个长度。
- 第 6 个值 - 8 个长度。
- 第 7 个值 - 2 个长度。
接收到的典型格式示例:
1000|2014|1|AP|1|1
请注意,典型格式不包括第 7 个值。在这些情况下,它应该默认为“00”。其他字段也不用前导零填充。这是我的方法。
//string buildcontentfromfile = the contents of each file that I receive and read
char[] delimiter = new char[] {'|'};
string[] contents = buildcontentfromfile.Split(delimiter);
if(contents[0].Length == 4)
{
if(contents[1].Length == 4)
{
if(contents[2].Length == 2)
{
if(contents[3].Length == 2)
{
if(contents[4].Length == 1)
{
if(contents[5].Length == 8)
{
if(contents[6].Length == 2)
{
}
}
}
}
}
}
}
这将处理“完美格式”,当然我需要添加更多逻辑来解决如何接收它们的“典型格式”,例如检查第 7 个值,并将前导 0 添加到需要它们的字段,以及长度。但我什至以正确的方式接近这个吗?有没有更简单的过程来做到这一点?谢谢!
请您参考如下方法:
使用正则表达式:
var re = new Regex("\d{4}\|\d{4}\|\d\d\|\w\w\|\d\|\d{8}\|\d\d");
var valid = re.IsMatch(input);
