[英]How to replace single quote within a string with two single quotes in java?
[英]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("\"\"", "\"");
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.