簡體   English   中英

如何在Java String中用單個雙引號替換兩個雙引號?

[英]How to replace two double quotes with a single double quote in Java String?

我正在讀取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();
    }

}

使用String#replace(CharSequence, CharSequence)

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

http://ideone.com/xPQqL

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM