I want to split the file in the picture and i can't because of the lines...The output i get is all together.What is the right command in regex to split even if there is a new line ?
-
2Please post the code and file content as text instead of picture. [edit] the question accordingly. See [Discourage screenshots of code and/or errors](https://meta.stackoverflow.com/q/303812/4391450) – AxelH May 02 '18 at 09:55
2 Answers
This should do:
protasi[] = string.split("\\r?\\n");
split("\n")
won't work because you need to provide a back-slash for \n
which becomes \\n
. I'd also added \\r
which is what we should use for newline/carriage return.

- 3,699
- 2
- 19
- 29
-
When the String is given as a variable it works but if i read it from a text file it doesn't – Nicolas Neofytou May 02 '18 at 10:01
-
Please explain why this solution should be valid in the answer. This would help OP to understand his mistake and don't do it again. – AxelH May 02 '18 at 10:11
-
PS: check [Java regex escaped characters](https://stackoverflow.com/q/45882306/4391450). – AxelH May 02 '18 at 10:55
-
You are reading the file using a Scanner
to get each line.
while(sc.hasNextLine())
You append the StringBuffer
with each line (without a separators).
sb.append(sc.nextLine())
So at that point, a file with :
foo
bar
Would give a StringBuffer
with
sb.toString(); //foobar
So there is not line separator left... Instead, do that with the Scanner
.
while(sc.hasNextLine()){
String s = sc.nextLine();
System.out.println(s):
sb.append(s);
}
Last thing, please close every Scanner
you open with sc.close()
when you are done with them (that's a good practice to have).
EDIT:
If you want to keep that logic, simply append with a line separator after each lines:
while(sc.hasNextLine()){
sb.append(sc.nextLine()).append("\n");
}
That way, you will always have a line separator and the split will work
Quick example of what this would look like :
StringBuffer sb = new StringBuffer();
sb.append("foo").append("\n")
.append("bar").append("\n"); //fake "file reading"
String[] result = sb.toString().split("\n");
for(String s : result){
System.out.println(s);
}
foo
bar

- 14,325
- 2
- 25
- 55