2014-12-05 21 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