23

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

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.

Ralph
  • 31,584
  • 38
  • 145
  • 282

6 Answers6

30

Java String method trim removes whitespace from beginning and end:

scala> println("<"+"  abc  ".trim+">")
<abc>
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • 9
    But that will only remove the whitespace from the first and lines lines, respectively, of a multi-line string. – Ralph May 18 '11 at 19:51
27

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

kassens
  • 4,405
  • 1
  • 26
  • 26
7

Split 'n' trim 'n' mkString (like a rock'n'roller):

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
user unknown
  • 35,537
  • 11
  • 75
  • 121
  • 1
    Note: split("\n") uses regex matching. Using split('\n') instead seems to convey intended meaning better (there will be no performance difference in recent world, as split is special casing for single character patterns anyway - see [Java split String performances](http://stackoverflow.com/a/11002374/16673). – Suma Feb 27 '15 at 14:46
2

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"))
Ian McLaird
  • 5,507
  • 2
  • 22
  • 31
1

Perhaps: s.lines.map(_.reverse.stripMargin.reverse).mkString("\n") or with System.getProperty("line.separator") instead of "\n"?!

Peter Schmitz
  • 5,824
  • 4
  • 26
  • 48
-2
str.reverse.dropWhile(_ == ' ').reverse
Det
  • 3,640
  • 5
  • 20
  • 27