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");
}
A new method
lines
has been introduced toString
class in java-11, which returnsStream<String>
Here are a few examples:
String#lines()
There are three different conventions (it could be said that those are de facto standards) to set and display a line break:
carriage return
+line feed
line feed
carriage return
In some text editors, it is possible to exchange one for the other:
The simplest thing is to normalize to
line feed
and then split.In
JDK11
theString
class has alines()
method:Further, the documentation goes on to say:
With this one can simply do:
then if you want an array:
Given this method returns a Stream it upon up a lot of options for you as it enables one to write concise and declarative expression of possibly-parallel operations.
If, for some reason, you don't want to use
String.split
(for example, because of regular expressions) and you want to use functional programming on Java 8 or newer:There is new boy in the town, so you need not to deal with all above complexities. From JDK 11 onward, just need to write as single line of code, it will split lines and returns you Stream of String.
Some references. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#lines() https://www.azul.com/90-new-features-and-apis-in-jdk-11/
I hope this will be helpful to someone. Happy coding.
The above code doesnt actually do anything visible - it just calcualtes then dumps the calculation. Is it the code you used, or just an example for this question?
try doing textAreaDoc.insertString(int, String, AttributeSet) at the end?