0

in windows following regex pattern is working: ("\r\n\r\n?\n\r") But I tried with forward slashes, but not working on server. Sample Data to split:

ABC
XYZ


NMB
YHJ

VGH

So, after splitting above data we want 2 arrays of string like

string[0] = ABC
XYZ
string[1] = NMB
YHJ

VGH
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
User22
  • 1
  • 1
    why forward slashes? try double backward slashes – Scary Wombat Feb 01 '19 at 07:54
  • You might be a bit confused between directory separators and escape characters (backslashes) . The former is different across OSs, the latter is always the same. – Federico klez Culloca Feb 01 '19 at 07:57
  • Why are there only two entries in the output array? I would have expected three. Please explain your logic here. – Tim Biegeleisen Feb 01 '19 at 07:57
  • Also, you might find [this](https://stackoverflow.com/questions/3516957/how-do-i-use-system-getpropertyline-separator-tostring/3517108) interesting – Federico klez Culloca Feb 01 '19 at 08:01
  • Since Java 8 regex supports `\R` to represent many form of line separators. So try maybe with `split("\\R{2}")` (`{2}` shows better IMO that you want exactly two line separators). – Pshemo Feb 01 '19 at 08:56

2 Answers2

0

the line separator is different in different os. you should get line separator first.

System.getProperty("line.separator")
denny
  • 44
  • 2
  • A good suggestion, but this doesn't explain how to generate the output the OP wants here. – Tim Biegeleisen Feb 01 '19 at 08:00
  • Actually, the separator will usually depend on OS where the file was created, which can easily be a different computer than where it's read. It's better to support both (all?) line separator formats unless you know for sure what the separator is in your file. – Jiri Tousek Feb 01 '19 at 08:12
0

Ok, suppose we have a string and want to separate it:

String s = "ABC\nXYZ\n\n\nNMB\nYHJ\n\nVGH";
String separator = System.getProperty("line.separator");
String[] results = s.split(separator + separator);
System.out.println(results[0]);
// returns ABC
//         XYZ

Also you maybe want to split them again:

for (String res : results) {
    System.out.println(res.split(separator)[0]);
    // returns ABC
 }
coffman21
  • 943
  • 11
  • 18