Split Java String by New Line

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

    You don't have to double escape characters in character groups.

    For all non empty lines use:

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

    String#split​(String regex) method is using regex (regular expressions). Since Java 8 regex supports \R which represents (from documentation of Pattern class):

    Linebreak matcher
    \R         Any Unicode linebreak sequence, is equivalent to \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]

    So we can use it to match:

    • \u000D\000A -> \r\n pair
    • \u000A -> line feed (\n)
    • \u000B -> line tabulation (DO NOT confuse with character tabulation \t which is \u0009)
    • \u000C -> form feed (\f)
    • \u000D -> carriage return (\r)
    • \u0085 -> next line (NEL)
    • \u2028 -> line separator
    • \u2029 -> paragraph separator

    As you see \r\n is placed at start of regex which ensures that regex will try to match this pair first, and only if that match fails it will try to match single character line separators.


    So if you want to split on line separator use split("\\R").

    If you don't want to remove from resulting array trailing empty strings "" use split(regex, limit) with negative limit parameter like split("\\R", -1).

    If you want to treat one or more continues empty lines as single delimiter use split("\\R+").

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