删除字符串regex java中逗号后的空格

wfypjpf4  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(422)

我有一个字符串,其中包含逗号分隔的数据:

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
5fjcxozz

5fjcxozz1#

正如您在评论中提到的,您希望在将值写入csv之前修剪这些值。这可以通过设置 withTrim -选择权 CSVFormat :

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

相关问题