Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java(android): How to I split a string by every two line breaks?

I have tried using string.split("\n\n") but it does not work. Anyone has any solution? thanks in advance

like image 557
soulless Avatar asked Jul 24 '15 10:07

soulless


People also ask

How do you separate text on Android?

split() is documented with TextUtils. split(): String. split() returns [''] when the string to be split is empty.

How do I split a string by next line?

To split a string on newlines, you can use the regular expression '\r?\ n|\r' which splits on all three '\r\n' , '\r' , and '\n' . A better solution is to use the linebreak matcher \R which matches with any Unicode linebreak sequence. You can also split a string on the system-dependent line separator string.

How do I split a string into multiple parts?

Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.

How do you break apart a string in Java?

split("-"); We can simply use a character/substring instead of an actual regular expression. Of course, there are certain special characters in regex which we need to keep in mind, and escape them in case we want their literal value. Once the string is split, the result is returned as an array of Strings.


2 Answers

First of all you should escape the \ with another \ like this:

string.split("\\n\\n");

Another way is using system default line separator:

string.split(System.getProperty("line.separator")+"{2}");

or you can try mix this:

string.split("(\\r\\n|"+System.getProperty("line.separator")+")+");

split need RegExp, so you can try variants for your problem.

And don't forget that sometimes new line is not only \n symbol, for Windows files it can be \r\n char sequence.

like image 99
0xFF Avatar answered Sep 23 '22 19:09

0xFF


You should escape the \ with another \ so try :-

string.split("\\n\\n");
like image 38
AnkeyNigam Avatar answered Sep 19 '22 19:09

AnkeyNigam