I'm reading a long line of info from a text file that looks exactly like this:
Sebastien 5000\\Loic 5000\\Shubhashisshh 5000\\Thibaullt 5000\\Caroo 5000\\Blabla 5000\\Okayyy 5000\\SebCed 5000\\abusee 5000\\omg 5000\\
It's supposed to be high scores with the names of users. When I print out the line, it looks exactly like it should, but when I print out the array after using split("\\\\")
, it looks like this:
[Sebastien 5000, , Loic 5000, , Shubhashisshh 5000, , Thibaullt 5000, , Caroo 5000, , Blabla 5000, , Okayyy 5000, , SebCed 5000, , abusee 5000, , omg 5000]
The problem is that Array[0]
is fine but Array[1]
is empty, as are Array[3]
, Array[5]
, etc.
Here is my code. What's wrong with it?
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(path));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = null;
try {
line = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("LINE = "+line);
String[] scores = line.split("\\\\");
System.out.println("Mode = "+mode+Arrays.toString(scores));
That's because "\\\\"
is being parsed as \\
and the split method uses a regular expression, so \\
is becoming \
, then Sebastien 5000\\Loic 5000
will result in [Sebastien 5000,,Loic 5000]
Do this instead: "\\\\\\\\"
Just for fun, aside José Roberto solution, you can also use some alternative expressions (and lots others):
Two consecutive backslashes (same that in José's, but using a quantifier):
String[] scores = line.split("\\\\{2}");
Two consecutive Non-Word Characters:
String[] scores = line.split("\\W{2}");
Two consecutive punctuation chars:
String[] scores = line.split("\\p{Punct}{2}");
All of them produce the required output.
For more info on Regular expressions in Java:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With