Ralph
Ralph

Reputation: 32284

Scala strip trailing whitespace

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.

Upvotes: 23

Views: 34430

Answers (6)

Det
Det

Reputation: 3710

str.reverse.dropWhile(_ == ' ').reverse

Upvotes: -2

user unknown
user unknown

Reputation: 36229

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

Upvotes: 7

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297195

Java String method trim removes whitespace from beginning and end:

scala> println("<"+"  abc  ".trim+">")
<abc>

Upvotes: 30

Peter Schmitz
Peter Schmitz

Reputation: 5844

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

Upvotes: 1

Ian McLaird
Ian McLaird

Reputation: 5585

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

Upvotes: 2

kassens
kassens

Reputation: 4475

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

Upvotes: 28

Related Questions