简体   繁体   中英

Why replaceAll method is not working?

I read from file like this:

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

After that I try to call replaceAll method on every string in the list, but it doesn't work with any regex and replacement string. Although, when I apply replaceAll with the same arguments to a string that I assign in code, it works fine. The strings look like this: "Hello","World","!!!"

Edit:

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);

The file consists of strings like that:

"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"

Here is the exact code I'm using: http://pastebin.com/GhhrRWAU

And here is the file I'm trying to parse: http://www.fileconvoy.com/dfl.php?id=g450e5a3e83854bdc999643999f2ceb8c622d6abf2

After that I try to call replaceAll method on every string in the list

The replaceAll() method does not update the existing String. It creates a new String.

So you need to update the List with your newly created String:

String testing = "some text";
//testing.replaceAll(...); // this doesn't work
testing = testing.replaceAll(....);

RegEx is always a headache for me, too. Actually your regex expression is almost correct (you can check it on https://regex101.com/ , for example). But this is Java and you should use inline modifier:

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);

Output:

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

BTW, \\i modifier is useless here, because \\w already matches [a-zA-Z0-9_]

EDIT Your file contains non-Latin characters, so you can use Regex groups instead:

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM