在保留换行符的同时修剪字符串

时间:2020-03-27 01:19:50

标签: regex string kotlin removing-whitespace

用于 String trim()方法返回一个字符串,该字符串除去了前导和尾随空格,还包括换行符('\n')。如何在保持换行符的同时获得trim()功能?

例如:"\n this is new line "-> "\nthis is new line"

2 个答案:

答案 0 :(得分:3)

您可以改为使用replaceAll

修改

    String str = "\n     this is new line    ";
    str = str.replaceAll("\n\\s+", "\n").replaceAll("\\s+$", "");

    System.out.println(str);

输出

这是新行

答案 1 :(得分:1)

fun main() {
  var str = "\n     this is new line    "
  str = str
    .replace("\n\\s+".toRegex(), "\n")
    .replace("\\s+$".toRegex(), "")
  println(str)
}

我想,那就是你想要的