使用replaceAll()输出错误

时间:2017-02-09 22:48:45

标签: java

我有一个格式如下的csv文件:

1,,3,4
3,4,,0
2,,4,2

我正在将该文件读入名为text的String变量中。然后,这样做

String newText = text.replaceAll("","0");

在我的输出中,它将no值元素替换为0,这是我想要的,但它也在具有值的元素之前和之后追加0。

010
0
030
040
030
040
0
000
020
0
040
020

感谢任何帮助!

编辑:这是我的其余代码用于确认。

import java.lang.*;

public class DataMatrix {

    private double[][] dMatrix; 

    public DataMatrix(String text) {

        String[] line = text.split("\n");
        // Creates an array for the CSV file
        String[][] sMatrix = new String[line.length][];

        for(int i=0; i < line.length; i++)
            sMatrix[i] = line[i].split(",");

        /*for(int j=0; j < sMatrix.length; j++) {
            for(int x=0; x <= line.length; x++) {
                if(sMatrix[j][x] !=*/ 

        System.out.println("Original String: ");

        for(int x=0; x < sMatrix.length; x++) {
            for(int j=0; j <= line.length; j++) {
                System.out.println(sMatrix[x][j]);
            }
        }

        dMatrix = new double[sMatrix.length][];
        System.out.println("Converted to double: ");

        for(int x=0; x < sMatrix.length; x++) {
            dMatrix[x] = new double[sMatrix[x].length];
            for(int j=0; j <= sMatrix.length; j++) {

                dMatrix[x][j] = Double.parseDouble(sMatrix[x][j]);
                System.out.println(dMatrix[x][j]);
            }
        }
    }

    public void avgRowValue() {

        double tempTotal = 0;

        for(int x=0; x < dMatrix.length; x++) {
            System.out.println("***********************************");
            System.out.println("The average for row "+(x+1)+" is: ");

            for(int i=0; i < dMatrix[x].length;i++) {
                tempTotal += dMatrix[x][i];
            double rowAvg = tempTotal / dMatrix[x].length;
            System.out.println(rowAvg);
            tempTotal = 0;
            }
        }

    }

    public void avgColValue() {

        double tempTotal = 0;

        for(int x=0; x < dMatrix[0].length; x++) {
            System.out.println("**************************************");
            System.out.println("The average for column "+(x+1)+" is: ");

            for(int i=0; i <= dMatrix.length-1; i++)
                tempTotal += dMatrix[i][x];
            double colAvg = tempTotal / dMatrix.length;
            System.out.println(colAvg);
            tempTotal = 0;
        }
    }

    public void overallAvgValue() {

        double tempTotal = 0;
        int count = 0;

        for(int x=0; x < dMatrix.length; x++) {
            for(int i=0; i <= dMatrix.length; i++) {
                tempTotal += dMatrix[x][i];
                count++;
            }
        }
        double overallAvg = tempTotal / count;
        System.out.println("The overall average for the data matrix is: "+overallAvg);
    }

    public void maxValue() {

        double maxValue = 0;

        for(int x=0; x < dMatrix.length; x++) {
            for(int i=0; i <= dMatrix.length; i++) {
                if(dMatrix[x][i] >= maxValue)
                    maxValue = dMatrix[x][i];
            }
        }
        System.out.println("The max value for the data matrix is: "+maxValue);
    }

    public void minValue() {

        double minValue = dMatrix[0][0];

        for(int x=0; x < dMatrix.length; x++) {
            for(int i=0; i <= dMatrix.length; i++) {
                if(dMatrix[x][i] <= minValue)
                    minValue = dMatrix[x][i];
            }
        }
        System.out.println("The min value for the data matrix is: "+minValue);
    }
}

和我的主要:

import java.util.*;

public class Assignment1{
    public static void main(String[] args){

        Scanner input = new Scanner(System.in);

            //Make sure the user passed the command line argument - and nothing else
             if (args.length != 1){
                System.out.println("Assignment1 takes exactly one command-line argument.");
                     System.out.println("Usage: java Assignment1 some_file.csv");
                 System.exit(0);
             }

             String csvFileName = args[0];

          //Instantiate my custom file reader
        CSVReader fileReader = new CSVReader();

       //Read the file into a string
        String text = fileReader.readFile(csvFileName);
    String newText = text.replaceAll("", "0");
    //Create a new instance of DataMatrix that takes in String CSV file and converts to double array
    DataMatrix matrix = new DataMatrix(newText);

    boolean done = false;
    while(done != true) {
        System.out.println("**********************");
        System.out.println("CSV Reader Menu: ");
        System.out.println("1. Display the average values of each individual row.");
        System.out.println("2. Display the averages value of each individual column.");
        System.out.println("3. Display the average of the entire data matrix.");
        System.out.println("4. Display the maximum value of the entire data matrix.");
        System.out.println("5. Display the minimum value of the entire data matrix.");
        System.out.println("0. Exit.");

        int choice = input.nextInt();
        switch(choice) {
            case 1: matrix.avgRowValue();
                break;
            case 2: matrix.avgColValue();
                break;
            case 3: matrix.overallAvgValue();
                break;
            case 4: matrix.maxValue();
                break;
            case 5: matrix.minValue();
                break;
            case 0: done = true;
                break;
            default: System.out.println("Invalid input.");
                break;
        }
    }//end of menu loop
    }//end of main
}//end of class

4 个答案:

答案 0 :(得分:3)

使用text.replaceAll("", "0"),您正在查找字符串中存在零长度子字符串的所有位置。对于任何字符串,这是在任意两个字符之间以及字符串的开头和结尾。

"12345".replaceAll("", "_")  // _1_2_3_4_5_

如果确实想要使用正则表达式,可以使用replaceAll("^$", "0"),其中^$是字符串的开头和结尾, 分别。或者,只需检查字符串是否为空:

String newText = text.isEmpty() ? "0" : text;

示例:

for (String s : "1,,23,4".split(",")) {
    System.out.println(s.isEmpty() ? "0" : s);  // prints 1, 0, 23, and 4
    System.out.println(s.replaceAll("^$", "0"));// prints 1, 0, 23, and 4
}

如果要将0插入到原始字符串中,即在使用split之前,可以使用不同正则表达式的分离来开始字符串,中间字符串和结束-of-string情况,使用lookahead and lookbehind断言,例如(?<=^|,)代表&#34;前面是字符串开头或,&#34;和(?=,|$)代表&#34;后跟,或结束-string&#34;:

String nums = ",1,,23,4,";
System.out.println(nums.replaceAll("(?<=^|,)(?=,|$)", "0"));
// output: 0,1,0,23,4,0

或者您可以在替换字符串中使用捕获组和组引用来将,转移到替换中。在这里,$10$2表示&#34;第一组,然后是0,然后是第二组&#34;:

System.out.println(nums.replaceAll("(^|,)(,|$)", "$10$2"));

答案 1 :(得分:1)

我喜欢在从csv文件读取时执行此操作,其成本远低于读取csv文件后的成本,因此我创建了一个csvreader和一个名为Line的数组,从csv逐行读取,并且如果字符串的长度大于0,则以此模式写入:0thatstring0,否则写为0

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] Line;
while ((Line = reader.readNext()) != null) {
    for(int i = 0 ; i < Line.length ; i++)
        if(Line[i].length>0) System.out.println(Line[i]);
        else System.out.println("0");
}

第二个方法,我不提供它,使用拆分方法并将每个字符串与","分开,执行replace方法并且它可以正常工作

答案 2 :(得分:0)

我建议使用OpenCSV这样的库来读取该文件,然后在遇到它们时替换空单元格。它会更强大。

答案 3 :(得分:0)

我了解text包含基于逗号分割行后单个列的值。您想将空字符串更改为“0”。

replaceAll()方法采用正则表达式。对于正则表达式,空字符串很奇怪。你想要的是text.replaceAll("^$", "0")