2

I am wondering how you can use the split method with this example considering the fact that that there is a line break in the file.

g3,g3,g3,c4-,a3-,g4-,r,r,r,g3,g3,g3,c4-,a3-,a4,g4-,r,r,r,c4,c4,c4,e4,r g4,r,a4,r,r,b4b,r,a4,f4,r,g4,r,r,g4#,r,g4,d4#,r,g4

I read the Pattern api and tutorials and think it should be like so.

line.split("(,\n)");

I also tried

line.split([,\n]);

and

line.split("[,\n]");

2 Answers2

1

lines may separated using \r or \n both of them, or even some other characters. Since Java 8 you can use \\R to represent line separators (more info). So you could try using

String[] arr = yourText.split(",|\\R");
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

As Pshemo notes, the 3rd option str.split("[,\n]") should work assuming the file ends each line with \n and not \r\n.

Additionally, how you read the file may affect your split argument.

If you are reading the file in with a BufferedReader, then going line by line with the readLine() method will automatically exclude any line-termination characters.

  • "*You need to escape the newline twice like \\n*" not quite. `\n` and `\\n` are treated same way in regex engine so `.split("[,\\n]");` is same as `.split("[,\n]");` which OP already tried. – Pshemo Oct 22 '17 at 02:27