Split Java String by New Line

前端 未结 20 1073
予麋鹿
予麋鹿 2020-11-22 00:56

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|

相关标签:
20条回答
  • 2020-11-22 01:52

    Maybe this would work:

    Remove the double backslashes from the parameter of the split method:

    split = docStr.split("\n");
    
    0 讨论(0)
  • 2020-11-22 01:52
    • try this hope it was helpful for you

     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");
    
    0 讨论(0)
  • 2020-11-22 01:53

    If you don’t want empty lines:

    String.split("[\\r\\n]+")
    
    0 讨论(0)
  • 2020-11-22 01:53

    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.

    public class MyClass {
    public static void main(String args[]) {
       Stream<String> lines="foo \n bar \n baz".lines();
       //Do whatever you want to do with lines
    }}
    

    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.

    0 讨论(0)
  • 2020-11-22 01:54

    After failed attempts on the basis of all given solutions. I replace \n with some special word and then split. For me following did the trick:

    article = "Alice phoned\n bob.";
    article = article.replace("\\n", " NEWLINE ");
    String sen [] = article.split(" NEWLINE ");
    

    I couldn't replicate the example given in the question. But, I guess this logic can be applied.

    0 讨论(0)
  • 2020-11-22 01:56

    String lines[] =String.split( System.lineSeparator())

    0 讨论(0)
提交回复
热议问题