How can we Split Java String by New Line?

0 votes

We tried to split text in a JTextArea using a regular expression to split the String by \n . But, this is not working. We also tried by using \r\n|\r|n and many other combinations 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) {
        e1.printStackTrace();
    }
    split = docStr.split("\\n");
}
Jun 5, 2018 in Java by sharth
• 3,330 points
478 views

2 answers to this question.

0 votes

This should cover your doubts:

String lines[] = string.split("\\r?\\n");

answered Jun 5, 2018 by parth295
• 4,640 points
0 votes

If you don’t want empty lines:
String.split("[\\r\\n]+")

answered Aug 22, 2018 by Daisy
• 8,050 points

Related Questions In Java

0 votes
3 answers

How can we use java.String.format in Scala?

String aString = "world"; int aInt = 20; String.format("Hello, ...READ MORE

answered Aug 29, 2018 in Java by Daisy
• 8,050 points
225 views
0 votes
1 answer

How can we nicely format a floating number into String by removing unnecessary zeros?

public static String fmt(double d) { if(d ...READ MORE

answered Jun 6, 2018 in Java by parth295
• 4,640 points
35 views
0 votes
1 answer

How can we encrypt a String in Java?

Let's assume the bytes to encrypt are ...READ MORE

answered Oct 26, 2018 in Java by Sushmita
• 6,880 points
18 views
0 votes
1 answer

How can we compare objects by multiple fields in Java?

You can implement a Comparator which compares two Person objects, and ...READ MORE

answered Jan 9 in Java by Daisy
• 8,050 points
51 views
0 votes
2 answers

Result of character addition in Java

Binary arithmetic operations on char and byte ...READ MORE

answered Aug 22 in Java by Sirajul
• 30,140 points
54 views
0 votes
1 answer

How do I create a Java string from the contents of a file?

If you're looking for an alternative that ...READ MORE

answered Apr 19, 2018 in Java by Rishabh
• 3,540 points
97 views
0 votes
2 answers

Counting no of Occurrence of a particular character inside a string in Java

We can find out the no. of ...READ MORE

answered Sep 7, 2018 in Java by Sushmita
• 6,880 points
287 views
0 votes
1 answer

Encode String to UTF-8

String objects in Java use the UTF-16 ...READ MORE

answered May 28, 2018 in Java by Rishabh
• 3,540 points
44 views
0 votes
1 answer

How can we split a comma separated String in Java?

String str = "..."; // write the ...READ MORE

answered Jun 12, 2018 in Java by parth295
• 4,640 points
59 views
0 votes
1 answer

How can I read a large text file line by line using Java?

// Open the file FileInputStream file = new ...READ MORE

answered May 2, 2018 in Java by parth295
• 4,640 points
50 views