2014-12-05 77 views
1

我有一个文件,其中包含管道分隔格式的内容。这是在WinForm应用程序中的C#中。完美格式拆分字符串并验证每个部分

实施例:

1000|2014|01|AP|1|00000001|00 
  • 第一值应始终为4的长度。
  • 第二值-4长度。
  • 第3个值 - 2个长度。
  • 第4个值 - 2个长度。
  • 第5个值 - 1个长度。
  • 第6个值-8长度。
  • 第7个值 - 2个长度。典型格式的

实施例被接收:

1000|2014|1|AP|1|1 

注意,典型格式不包括第七值。在这些情况下,它应该默认为“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) 
        { 
        } 
       } 
      } 
     } 
     } 
    } 
} 

这将照顾“完美格式”的,当然我需要添加更多的逻辑来解决它们是如何获得,比如检查第七届价值“的典型格式”,并添加将0引入需要它们的字段以及长度。但我是否以正确的方式接近这一点?有没有更简单的过程来做到这一点?谢谢!

+1

http://codereview.stackexchange.com/ – 2014-12-05 17:29:23

+0

也许与子字符串? – CularBytes 2014-12-05 17:31:32

+0

我会看看使用正则表达式。他们擅长评估字符类型和字符串部分的长度。 – gmlacrosse 2014-12-05 17:33:41

回答

2

使用正则表达式:

var re = new Regex("\d{4}\|\d{4}\|\d\d\|\w\w\|\d\|\d{8}\|\d\d"); 
var valid = re.IsMatch(input); 
+0

说明:\ d = number,\ w = alfanumeric字符,\ | =管道字符,{x} =最后一个令牌x的次数 – 2014-12-05 17:41:15

+0

感谢您的解释。我明天会试试这个,希望它适合我想做的事情。 – Jayarikahs 2014-12-07 20:52:00

2

只是从我的头顶(我还没有在实际的机器上尝试这个)

var input = "1000|2014|01|AP|1|00000001|00"; 

var pattern = new int[] {4, 4, 2, 2, 1, 8, 2}; 

// Check each element length according to it's input position. 
var matches = input 
    .Split('|') 
     // Get only those elements that satisfy the length condition. 
    .Where((x, index) => x.Count() == pattern(index)) 
    .Count(); 

if (matches == pattern.Count()) 
    // Input was as expected. 
+0

感谢您的回复。我会先尝试正则表达式,但是如果我无法正常工作,那么我会给你的建议一个运行。 – Jayarikahs 2014-12-07 20:52:33