【发布时间】:2020-03-28 01:41:02
【问题描述】:
String 的 trim() 方法返回一个删除了前导和尾随空格的字符串,其中还包括换行符 ('\n')。我们如何在保持换行符的同时获得trim() 功能?
例如:"\n this is new line " -> "\nthis is new line"
【问题讨论】:
标签: regex string kotlin removing-whitespace
String 的 trim() 方法返回一个删除了前导和尾随空格的字符串,其中还包括换行符 ('\n')。我们如何在保持换行符的同时获得trim() 功能?
例如:"\n this is new line " -> "\nthis is new line"
【问题讨论】:
标签: regex string kotlin removing-whitespace
你可以用 replaceAll 代替
编辑
String str = "\n this is new line ";
str = str.replaceAll("\n\\s+", "\n").replaceAll("\\s+$", "");
System.out.println(str);
输出
这是新行
【讨论】:
replace 而不是 replaceAll。
"\n "并一直这样做直到String的大小没有改变
kotlin中找到对应replaceAll的。
CharSequence#replace(Regex,String)。
fun main() {
var str = "\n this is new line "
str = str
.replace("\n\\s+".toRegex(), "\n")
.replace("\\s+$".toRegex(), "")
println(str)
}
我想,这就是你想要的
【讨论】: