2016-05-13 34 views
3

我是CSV解析的新手。我有一個CSV文件,第三列(描述字段)可能有一個或多個6位數字以及其他值。我需要過濾掉這些數字並將它們寫入每行對應的相鄰列。使用Java過濾掉CSV文件中的數字

如:

3rd column      4th column 
=============     =========== 
123456adjfghviu77    123456 

shgdasd234567     234567 

123456abc:de234567:c567890d  123456-234567-567890 

12654352474       

請幫助。這是我迄今爲止所做的。

 String strFile="D:/Input.csv"; 
     CSVReader reader=new CSVReader(new FileReader(strFile)); 

     String[] nextline; 
     //int lineNumber=0; 
     String str="^[\\d|\\s]{5}$"; 
     String regex="[^\\d]+"; 

     FileWriter fw = new FileWriter("D:/Output.csv"); 
     PrintWriter pw = new PrintWriter(fw); 


     while((nextline=reader.readNext())!=null){ 
      //lineNumber++; 
      //System.out.println("Line : "+lineNumber); 
      if(nextline[2].toString().matches(str)){ 
      pw.print(nextline[1]); 
      pw.append('\n'); 
      System.out.println(nextline[2]); 
      }    

     } 
     pw.flush(); 
+3

*可能有一個或一個以上6位數字與其他值一起* - >你必須向我們展示了樣品的輸入和輸出 – TheLostMind

+0

對不起......更新與樣品輸入的問題。 –

+1

問題是,你只是檢查是否正則表達式模式_matches_,然後打印該行,如果它。您需要使用捕獲組並打印_submatches_。 –

回答

2

我建議只匹配6位數的塊,並建立一個新的字符串收集匹配時:

String s = "123456abc:de234567:c567890d"; 
StringBuilder result = new StringBuilder(); 
Pattern pattern = Pattern.compile("(?<!\\d)\\d{6}(?!\\d)"); // Pattern to match 6 digit chunks not enclosed with digits 
Matcher matcher = pattern.matcher(s); 
while (matcher.find()){ 
    if (result.length() == 0) {    // If the result is empty 
     result.append(matcher.group(0));  // add the 6 digit chunk 
    } else { 
     result.append("-").append(matcher.group(0)); // else add a delimiter and the digits after it 
    } 
} 
System.out.println(result.toString());  // Demo, use this to write to your new column 

參見Java demo

更新:我已經從0變化圖案到"(?<!\\d)\\d{6}(?!\\d)",以確保我們只匹配而不是用其他數字括起來的6位塊。

regex demo

+0

感謝這一點,但它不斷追加值..我需要單獨的行單獨輸出 –

+1

@RiteshSatapathy:想象一下,你讀了一個問題來自陌生人。我應該從您的評論中瞭解什麼? *我需要從別的東西獲得一些東西,把它變成更多的東西*。請具體說明。 *匹配*的標準*是什麼? 6位大塊不包含其他數字?然後你需要一個'「(?<!\\ d)\\ d {6}(?!\\ d)」'正則表達式。 –

+0

此外,每次閱讀新行時,都需要重置StringBuilder(只需將它放在代碼中的正確位置)。 –

1

所有右擊,這是你需要做的就是數字在第三列是什麼:

while((nextline=reader.readNext())!=null){ 
    //For every column (columnNumber) 
    String digitsInColumn = nextline[columnNumber].replaceAll("\\D+",""); 
    // Your treatment 

} 
+0

我同意這一點,但如果該單元格有多個6位數值..我的意思是這樣的'123456hdfhg,sdfg567890' ...它會將它們追加在一起..但我不希望這樣,我希望它們分開在另一個cell –

+0

好吧,它不能像你的例子中的逗號,在其他地方它不會是同一列。在你的解釋中。你所說的「可能有一個或多個6位數字以及其他值,我需要過濾掉這些數字並將它們寫入每行對應的相鄰列。 digitsInColumn將在這個列中有數字,你必須爲每一列做相同的事情來獲得數字 –

+0

@RiteshSatapathy你將如何在輸出csv文件的下一列追加123456adjfghviu77234567的結果?你的問題缺乏這個用例的規範 –