How to trim ending blanks of a string?

You can do it with a regex:

"  string  ".replaceAll("\\s+$", "");
res0: java.lang.String = "  string"

Another possible way is to use method dropWhile from rich String class named StringOps

scala> val y = "   abcd   ".reverse.dropWhile(_ == ' ').reverse
y: String = "   abcd"

If you need to trim spaces from the beginning of string just remove reverse methods:

scala> val y = "   abcd   ".dropWhile(_ == ' ')
y: String = "abcd   "

Without external dependencies and only end trimming:

scala> val s = "   test   \t"
s: java.lang.String = "   test      "

scala> val Regex = """^(.*?)\s*$""".r
Regex: scala.util.matching.Regex = ^(.*?)\s*$

scala> val Regex(trimmed) = s
trimmed: String = "   test"

Tags:

Scala