How to remove newlines from beginning and end of a string?

前端 未结 12 627
旧巷少年郎
旧巷少年郎 2020-11-29 03:22

I have a string that contains some text followed by a blank line. What\'s the best way to keep the part with text, but remove the whitespace newline from the end?

12条回答
  •  既然无缘
    2020-11-29 03:55

    String trimStartEnd = "\n TestString1 linebreak1\nlinebreak2\nlinebreak3\n TestString2 \n";
    System.out.println("Original String : [" + trimStartEnd + "]");
    System.out.println("-----------------------------");
    System.out.println("Result String : [" + trimStartEnd.replaceAll("^(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])|(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])$", "") + "]");
    
    1. Start of a string = ^ ,
    2. End of a string = $ ,
    3. regex combination = | ,
    4. Linebreak = \r\n|[\n\x0B\x0C\r\u0085\u2028\u2029]

提交回复
热议问题