2016-08-22 2 views
1

여러 구분 기호 및 다른 빈 라인의 길이를 기준으로 분할을 사용하여 :나는 다음과 같은 포함 일부의 .dat 파일이

<D,E> 200 200 799 1220 No [<805,1380,Voltage,3,2>] 
<A,C> 300 300 415 1230 Yes [<417,1340,Voltage,3,0><415,1230,Current,3,1>] 
<D,B> 200 200 799 122 No [<80,137,Voltage,3,2>] 
    . 
    . 

내가 각 행, 세 번째 요소의 내용을 가지고 싶습니다을; 첫 번째 줄에는 200, 두 번째 줄에는 300, 세 번째 줄에는 200입니다. 또한 0과 1 (두 개를 추가하고 싶습니다)을 두 번째 줄에, 두 번째 줄을 1과 3 줄에두고 싶습니다.

I는 그것이 temp.length은 동일한 크기를 가질 때, 그것은 또한 작동 작동 제 라인이

while ((line = file.readLine()) != null) { 

     if (line != null && !line.trim().isEmpty()) { 
      line = line.replace(" ", "|"); 
      line = line.replace("||", ""); 
      System.out.println(line); 

      String[] temp = line.split("|"); 
      String temp1 = ""; 
      String temp2 = ""; 

      //System.out.println(temp[52]); 
      if (temp.length == 55) { 
       temp1 = temp[11] + temp[12] + temp[13]; 
       temp2 = temp[52]; 


      } else if (temp.length==52){ 
       int len = temp.length; 
       temp1 = temp[11] + temp[12] + temp[13]; 
       temp2 = temp[temp.length - 3]; 

      } 

}

시도; 그러나, 내 라인 항상 같은 길이를하지 않습니다. 좋은 방법으로 라인을 분할하면 필요한 요소를 가질 수 있습니다.

+0

'시스템을 참조하십시오. out.println (line.split ("\\ s +") [2]); ' –

+0

* 또한 0과 1을 추가하고 싶습니다. (정수를 추가하고 싶습니다) * - 숫자를 정수로 추가 하시겠습니까? 또는 수레? 또는 문자열로 연결하십시오. –

+0

http://ideone.com/M1CFuz를 참조하십시오. –

답변

1

는 먼저 공백)가 > 전에 숫자의 덩어리를 추출 ([0-9]+)> 같은 간단한 정규식을 사용하여 다음 (.split("\\s+") 사용)로 문자열을 분할 할 수 있습니다

// Init the regex here 
String rx = "([0-9]+)>"; 

// Then the part where you read the lines 
String line = reader.readLine(); 
while (line != null) { 
    String[] chunks = line.split("\\s+"); // Split with whitespace 
    if (chunks.length > 2) { // chunks[2] = 200/300 values 
     Matcher m = p.matcher(line); // Init Matcher to find all numbers at the end of > 
     int val = 0; 
     while (m.find()) { // Find multiple occurrences numbers before > 
      val += Integer.parseInt(m.group(1)); // Group 1 contains the number, summing up 
     } 
     res.add(chunks[2]); 
     res.add(Integer.toString(val)); 
    } 
    line = reader.readLine(); 
} 
System.out.println(res); // => [200, 2, 300, 1, 200, 2] 

IDEONE Java demo

관련 문제