I'm trying to split text in a JTextArea
using a regex to split the String by \n
However, this does not work and I also tried by \r\n|\r|n
and many other combination of regexes.
Code:
public void insertUpdate(DocumentEvent e) {
String split[], docStr = null;
Document textAreaDoc = (Document)e.getDocument();
try {
docStr = textAreaDoc.getText(textAreaDoc.getStartPosition().getOffset(), textAreaDoc.getEndPosition().getOffset());
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
split = docStr.split("\\n");
}
For preserving empty lines from getting squashed use:
All answers given here actually do not respect Javas definition of new lines as given in e.g. BufferedReader#readline. Java is accepting
\n
,\r
and\r\n
as new line. Some of the answers match multiple empty lines or malformed files. E..g.<sometext>\n\r\n<someothertext>
when using[\r\n]+
would result in two lines.In contrast, the answer above has the following properties:
split
method is using regex (regular expressions). Since Java 8 regex supports\R
which represents (from documentation of Pattern class):So we can use it to match:
\u000D\000A
->\r\n
pair\n
)\t
which is\u0009
)\f
)\r
)As you see
\r\n
is placed at start of regex which ensures that regex will try to match this pair first, and only if that match fails it will try to match single character line separators.So if you want to split on line separator use
split("\\R")
.If you don't want to remove from resulting array trailing empty strings
""
usesplit(regex, limit)
with negativelimit
parameter likesplit("\\R", -1)
.If you want to treat one or more continues empty lines as single delimiter use
split("\\R+")
.This should be system independent
String lines[] =String.split( System.lineSeparator())