patternjavaCritical
Split Java String by New Line
Viewed 0 times
javalinesplitstringnew
Problem
I'm trying to split text in a
Code:
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");
}Solution
This should cover you:
There are only really two newlines (UNIX and Windows) that you need to worry about, and this Regex covers both cases.
String lines[] = string.split("\\r?\\n");There are only really two newlines (UNIX and Windows) that you need to worry about, and this Regex covers both cases.
Code Snippets
String lines[] = string.split("\\r?\\n");Context
Stack Overflow Q#454908, score: 873
Revisions (0)
No revisions yet.