如何用Java String中的单个双引号替换两个双引号?

时间:2012-08-09 19:30:05

标签: java

我正在阅读CSV文件,并且有一些像

这样的值
field 1   field 2           field 3
1        test case1         expecting one, and \"two\", and three

将文件读入StringBuilder并转换toString()后,我将文件内容拆分为:string.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");

在迭代字符串时,我得到以下值: -

1
test case1
expecting one, and ""two"", and three

我怎样才能用两个双引号替换两个双引号,如“两个”

这是我的代码: -

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class csvStringParser {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub


          String path = "E:/spc.csv";

            String read = readFile(path);
            System.out.println("content of the file before \" = \n"  +read);



//      System.out.println("content of the file after= \n"  +read);

        String[] tokens = read.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
            for(int i = 0;i<tokens.length;i++) {
                String abc = tokens[i].replace("\"\"", "\"");

           //   if(abc.length()>2){
                if(abc.startsWith("\"") && abc.endsWith("\"")){ 
                abc = abc.substring(1, abc.length()-1);
                }
            //  } 

                System.out.println("> "+abc);
            }

    }

    public static String readFile( String file ) throws IOException {
        BufferedReader reader = new BufferedReader( new FileReader (file));
        String         line = null;
        StringBuilder  stringBuilder = new StringBuilder();
        String         ls = System.getProperty("line.separator");

        while( ( line = reader.readLine() ) != null ) {
            stringBuilder.append( line );
            stringBuilder.append( ls );
        }

        return stringBuilder.toString();
    }

}

2 个答案:

答案 0 :(得分:8)

使用String#replace(CharSequence, CharSequence)

String input = "this string \"\"has\"\" double quotes";
String output = input.replace("\"\"", "\"");

http://ideone.com/xPQqL

答案 1 :(得分:2)

String[] tokens = read.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for(int i = 0;i<tokens.length;i++)
    tokens[i]=StringEscapeUtils.unescapeCsv(tokens[i]);