string Scala条带尾随空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6046897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala strip trailing whitespace
提问by Ralph
The Scala String
method (in class StringOps
) stripMargin
removes leading whitespace from each line of a multi-line String
up to and including the pipe (|
) character (or other designated delimiter).
ScalaString
方法(在 class 中StringOps
)stripMargin
从多行的每一行中删除前导空格,String
直到并包括管道 ( |
) 字符(或其他指定的分隔符)。
Is there an equivalent method to remove trailing whitespace from each line?
是否有等效的方法可以从每行中删除尾随空格?
I did a quick look through the Scaladocs, but could not find one.
我快速浏览了 Scaladocs,但找不到。
回答by Daniel C. Sobral
Java String
method trim
removes whitespace from beginning and end:
JavaString
方法trim
从头到尾删除空格:
scala> println("<"+" abc ".trim+">")
<abc>
回答by kassens
You can easily use a regex for that:
您可以轻松地使用正则表达式:
input.replaceAll("""(?m)\s+$""", "")
The (?m)
prefix in the regex makes it a multiline regex. \s+
matches 1 or more whitespace characters and $
the end of the line (because of the multiline flag).
(?m)
正则表达式中的前缀使其成为多行正则表达式。\s+
匹配 1 个或多个空白字符和$
行尾(由于多行标志)。
回答by user unknown
Split 'n' trim 'n' mkString (like a rock'n'roller):
拆分 'n' 修剪 'n' mkString(就像摇滚乐):
val lines = """
This is
a test
a foolish
test
a
test
t
"""
lines.split ("\n").map (_.trim).mkString ("\n")
res22: String =
This is
a test
a foolish
test
a
test
t
回答by Ian McLaird
This might not be the most efficient way, but you could also do this:
这可能不是最有效的方法,但您也可以这样做:
val trimmed = str.lines map { s => s.reverse.dropWhile ( c => c == ' ').reverse.mkString(System.getProperty("line.seperator"))
回答by Peter Schmitz
Perhaps: s.lines.map(_.reverse.stripMargin.reverse).mkString("\n")
or with System.getProperty("line.separator")
instead of "\n"
?!
也许:s.lines.map(_.reverse.stripMargin.reverse).mkString("\n")
或者用System.getProperty("line.separator")
而不是"\n"
?!
回答by Det
str.reverse.dropWhile(_ == ' ').reverse