Split Java String by New Line

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

    A new method lines has been introduced to String class in java-11, which returns Stream

    Returns a stream of substrings extracted from this string partitioned by line terminators.

    Line terminators recognized are line feed "\n" (U+000A), carriage return "\r" (U+000D) and a carriage return followed immediately by a line feed "\r\n" (U+000D U+000A).

    Here are a few examples:

    jshell> "lorem \n ipusm \n sit".lines().forEach(System.out::println)
    lorem
     ipusm
     sit
    
    jshell> "lorem \n ipusm \r  sit".lines().forEach(System.out::println)
    lorem
     ipusm
      sit
    
    jshell> "lorem \n ipusm \r\n  sit".lines().forEach(System.out::println)
    lorem
     ipusm
      sit
    

    String#lines()

提交回复
热议问题