我有一个csv文件,每行有5个数字。
a line in csv:- 10003478,12228,7711479,15013889,3070120,5834262
我需要将此字符串转换为类似
的字符串expected:- 10003478,2/28/12228,4/79/7711479,8/89/15013889,1/20/3070120,2/62/5834262
在预期输出中,' /'周围的数字是每个数字的最后三位数。
例如:12228 - 最后三位数字是228,它们是这样分开的并且被制成2/28/12228
答案 0 :(得分:1)
您可以使用replaceAll
方法并将其保存为新的字符串:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws IOException {
// Read file
Path filePath = Paths.get("file.txt");
byte[] arr = Files.readAllBytes(filePath);
String content = new String(arr, Charset.defaultCharset());
// Replace
String newContent = new String(
content.replaceAll(",([0-9]+)([0-9]{1})([0-9]{2})", ",$2/$3/$1$2$3"));
System.out.println(newContent);
}
}
这会产生:
10003478,2/28/12228,4/79/7711479,8/89/15013889,1/20/3070120,2/62/5834262
答案 1 :(得分:0)
你可以有这样的模式:
,((\d+)(\d)(\d{2}))
并使用:
执行replaceAll
,$3/$4/$1
javascript中的示例:
console.log("10003478,12228,7711479,15013889,3070120,5834262".replace(/,((\d+)(\d)(\d{2}))/g, ",$3/$4/$1"));
答案 2 :(得分:0)
我不明白你为什么要使用正则表达式。相反,您只需读取文件并转换字符串并写回文件即可。下面是一个使用OpenCsv
的示例import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class JavaApplication22 {
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\uzochi\\desktop\\numbers.csv";
CSVReader reader = new CSVReader(new FileReader(path));
List<String[]> myEntries = reader.readAll();
for(String[] s : myEntries){
for(int i = 1; i<=5; i++){
String last3 = s[i].substring(s[i].length()-3,s[i].length());
last3 = last3.charAt(0)+"/"+last3.substring(1)+"/";
s[i] = last3+s[i];
}
System.out.println(Arrays.toString(s));
}
CSVWriter writer = new CSVWriter(new FileWriter(path), ',');
for(String[] s : myEntries){
writer.writeNext(s);
}
writer.close();
}
}