Read a single line text file, split into an array

I am reading a long line of information from a text file that looks something like this:

Sebastien 5000\\Loic 5000\\Shubhashisshh 5000\\Thibaullt 5000\\Caroo 5000\\Blabla 5000\\Okayyy 5000\\SebCed 5000\\abusee 5000\\omg 5000\\

It should be high with usernames. When I print the string, it looks as it should, but when I print 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] great, but Array[1] empty, like Array[3] , Array[5] , etc.

Here is my code. What is wrong with him?

  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)); 
+7
source share
3 answers

This is because "\\\\" parsed as \\ , and the method uses a regular expression, so \\ becomes \ , then the Sebastien 5000\\Loic 5000 will lead to [Sebastien 5000,,Loic 5000]

Do this instead: "\\\\\\\\"

+9
source

Just for fun, in addition to Jose Roberto's solution, you can also use some alternative expressions (and much more):

Two consecutive backslashes (same as Jose, but using a quantifier):

 String[] scores = line.split("\\\\{2}"); 

Two consecutive characters without words:

 String[] scores = line.split("\\W{2}"); 

Two consecutive punctuation characters:

 String[] scores = line.split("\\p{Punct}{2}"); 

All of them give the required result.

Learn more about regular expressions in Java:

+3
source

I would go further Nick:

line.split("\\\");

This view assumes that you are trying to split a line at every point where a double backslash appears - your code seems to be split into each alternating double slash, which explains the double commas between each name; therefore, between each divided part (that is, each of the sections between commas, there are two entries instead of one, so that one entry is just a comma). See if it works - good luck !!

M.

0
source

All Articles