我从这样的文件中读取:

List<String> list = Files.readAllLines(Paths.get("file.csv"));


之后,我尝试对列表中的每个字符串调用replaceAll方法,但不适用于任何正则表达式和替换字符串。虽然,当我将具有相同参数的replaceAll应用于在代码中分配的字符串时,它可以正常工作。
字符串如下所示:"Hello","World","!!!"

编辑:

List<String> res = Files.readAllLines(Paths.get("TimeTable.csv"));

String p = "^\"(\\w+) (\\w+) (\\w+) (?:.+)?\",\"(\\d+)\\.(\\d+)\\.(\\d+)\",\"(\\d+):(\\d+):(\\d+)\"(?:.*?)$/i";
String rep = "$6-$5-$4 ==> $7:$8 $1 $2 $3";
String s = res.get(1).replaceAll(p, rep);
System.out.print(s);


该文件包含如下字符串:

"AK Pz 310u PI-13-5","23.02.2015","07:45:00","23.02.2015","09:20:00","False","True","23.02.2015","07:40:00","2","Common","AK Pz 310u PI-13-5","Common"


这是我正在使用的确切代码:http://pastebin.com/GhhrRWAU

这是我要解析的文件:http://www.fileconvoy.com/dfl.php?id=g450e5a3e83854bdc999643999f2ceb8c622d6abf2

最佳答案

RegEx我也总是很头疼。实际上,您的正则表达式表达式几乎是正确的(例如,您可以在https://regex101.com/上对其进行检查)。但这是Java,您应该使用内联修饰符:

String p = "^\"(\\w+) (\\w+) (\\w+) (?:.+)?\",\"(\\d+)\\.(\\d+)\\.(\\d+)\",\"(\\d+):(\\d+):(\\d+)\"(?:.*?)$";
String rep = "$6-$5-$4 ==> $7:$8 $1 $2 $3";
String test = "\"AK Pz 310u PI-13-5\",\"23.02.2015\",\"07:45:00\",\"23.02.2015\",\"09:20:00\",\"False\",\"True\",\"23.02.2015\",\"07:40:00\",\"2\",\"Common\",\"AK Pz 310u PI-13-5\",\"Common\"";
String s = test.replaceAll(p, rep);
System.out.print(s);


输出:

2015-02-23 ==> 07:40 AK Pz 310u


顺便说一句,\i修饰符在这里是无用的,因为\w已经匹配[a-zA-Z0-9_]

编辑您的文件包含非拉丁字符,因此您可以改用Regex组:

List<String> res = Files.readAllLines(Paths.get("TimeTable.csv"));
String p = "(?i)^\"([\\p{L}_]+) (\\p{L}+) ([\\p{L}\\p{N}-_]+) (?:.+)?\",\"(\\d+)\\.(\\d+)\\.(\\d+)\",\"(\\d+):(\\d+):(\\d+)\"(?:.*?)$";
String rep = "$6-$5-$4 ==> $7:$8 $1 $2 $3";
for (String str : res){
    System.out.println(str.replaceAll(p, rep));
}

关于java - 为什么replaceAll方法不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29377783/

10-14 09:00