2016-05-13 88 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的结果?你的问题缺乏这个用例的规范 –