Split Java String by New Line

前端 未结 20 1109
予麋鹿
予麋鹿 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<String>

    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()

    0 讨论(0)
  • 2020-11-22 01:35

    If, for some reason, you don't want to use String.split (for example, because of regular expressions) and you want to use functional programming on Java 8 or newer:

    List<String> lines = new BufferedReader(new StringReader(string))
            .lines()
            .collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-11-22 01:35

    There are three different conventions (it could be said that those are de facto standards) to set and display a line break:

    • carriage return + line feed
    • line feed
    • carriage return

    In some text editors, it is possible to exchange one for the other:

    Notepad++

    The simplest thing is to normalize to line feedand then split.

    final String[] lines = contents.replace("\r\n", "\n")
                                   .replace("\r", "\n")
                                   .split("\n", -1);
    
    0 讨论(0)
  • 2020-11-22 01:36

    This should cover you:

    String lines[] = string.split("\\r?\\n");
    

    There's only really two newlines (UNIX and Windows) that you need to worry about.

    0 讨论(0)
  • 2020-11-22 01:37
    String.split(System.getProperty("line.separator"));
    

    This should be system independent

    0 讨论(0)
  • 2020-11-22 01:37

    The above code doesnt actually do anything visible - it just calcualtes then dumps the calculation. Is it the code you used, or just an example for this question?

    try doing textAreaDoc.insertString(int, String, AttributeSet) at the end?

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