我从这样的文件中读到:
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
答案 0 :(得分:1)
之后我尝试在列表中的每个字符串上调用replaceAll方法
replaceAll()
方法不会更新现有的String。它创建一个新的String。
因此,您需要使用新创建的字符串更新List:
String testing = "some text";
//testing.replaceAll(...); // this doesn't work
testing = testing.replaceAll(....);
答案 1 :(得分:1)
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));
}