Split Java String by New Line

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

    In JDK11 the String class has a lines() method:

    Returning a stream of lines extracted from this string, separated by line terminators.

    Further, the documentation goes on to say:

    A line terminator is one of the following: a line feed character "\n" (U+000A), a carriage return character "\r" (U+000D), or a carriage return followed immediately by a line feed "\r\n" (U+000D U+000A). A line is either a sequence of zero or more characters followed by a line terminator, or it is a sequence of one or more characters followed by the end of the string. A line does not include the line terminator.

    With this one can simply do:

    Stream stream = str.lines();
    

    then if you want an array:

    String[] array = str.lines().toArray(String[]::new);
    

    Given this method returns a Stream it upon up a lot of options for you as it enables one to write concise and declarative expression of possibly-parallel operations.

提交回复
热议问题