我有一个包含逗号分隔数据的字符串:
1, What is your name ?, Male, Cell no
2, From which country you belong, USA, Greetings
我使用这个正则表达式,但它不能完成任务:
str.replace(/s/g, "")
我如何将字符串转换为:
1,What is your name ?,Male,Cell no
2,From which country you belong,USA,Greetings
正如您在注释中提到的,您希望在将值写入CSV之前对其进行修剪。这可以通过在CSVFormat
:上设置withTrim
-选项来完成
CSVFormat csvFormat = CSVFormat.DEFAULT.withTrim();
try (FileWriter writer = new FileWriter("file.txt", false);
CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) {
csvPrinter.printRecord("1", " What is your name ?", " Male", " Cell no");
csvPrinter.printRecord("2", " From which country you belong", " USA", " Greetings");
}
file.txt
执行后的内容:
1,What is your name ?,Male,Cell no
2,From which country you belong,USA,Greetings