Split text file into Strings on empty line

后端 未结 6 1458
温柔的废话
温柔的废话 2021-02-15 16:12

I want to read a local txt file and read the text in this file. After that i want to split this whole text into Strings like in the example below .

Example : Lets say

6条回答
  •  日久生厌
    2021-02-15 16:54

    Godwin was on the right track, but I think we can make this work a bit better. Using the '[ ]' in regx is an or, so in his example if you had a \r\n that would just be a new line not an empty line. The regular expression would split it on both the \r and the \n, and I believe in the example we were looking for an empty line which would require a either a \n\r\n\r, a \r\n\r\n, a \n\r\r\n, a \r\n\n\r, or a \n\n or a \r\r

    So first we want to look for either \n\r or \r\n twice, with any combination of the two being possible.

    String.split(((\\n\\r)|(\\r\\n)){2}));
    

    next we need to look for \r without a \n after it

    String.split(\\r{2});
    

    lastly, lets do the same for \n

    String.split(\\n{2});
    

    And all together that should be

    String.split("((\\n\\r)|(\\r\\n)){2}|(\\r){2}|(\\n){2}");

    Note, this works only on the very specific example of using new lines and character returns. I in ruby you can do the following which would encompass more cases. I don't know if there is an equivalent in Java.

    .match($^$)
    

提交回复
热议问题