Split Java String by New Line

前端 未结 20 1089
予麋鹿
予麋鹿 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:49

    All answers given here actually do not respect Javas definition of new lines as given in e.g. BufferedReader#readline. Java is accepting \n, \r and \r\n as new line. Some of the answers match multiple empty lines or malformed files. E..g. \n\r\n when using [\r\n]+would result in two lines.

    String lines[] = string.split("(\r\n|\r|\n)", -1);
    

    In contrast, the answer above has the following properties:

    • it complies with Javas definition of a new line such as e.g. the BufferedReader is using it
    • it does not match multiple new lines
    • it does not remove trailing empty lines

提交回复
热议问题