Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala String trimming by a set of characters

Tags:

string

scala

Given any set of (trailing) characters, for instance

val s = "un".toSet

how to trim a string by s, namely,

"untidy stringnu".trimBy(s)
res: String = tidy string
like image 935
elm Avatar asked Feb 13 '23 20:02

elm


2 Answers

Scala has a dropWhile that solves half of the problem. It also has a dropRight that's an analog to drop for the right end of the collection. Unfortunately it doesn't have a dropWhileRight, though, so you have to get creative.

If you don't particularly care about efficiency, you can just drop the characters off the left end, reverse, repeat, and reverse again:

scala> "untidy stringnu".dropWhile(s).reverse.dropWhile(s).reverse
res0: String = tidy string

If you're sure that's going to be a bottleneck in your program (hint: it's probably not), you'll want some kind of imperative solution.

like image 144
Travis Brown Avatar answered Feb 16 '23 02:02

Travis Brown


The triple quotes are reflexive. As in pure reflex.

scala> val s = "undo"
s: String = undo

scala> val r = s"""[$s]*(.*?)[$s]*""".r
r: scala.util.matching.Regex = [undo]*(.*?)[undo]*

scala> def f(x: String) = x match { case r(y) => y case z => z }
f: (x: String)String

scala> f("nodu some string here...donuts are goodun")
res0: String = " some string here...donuts are g"

scala> f("undoundo")
res1: String = ""

or

scala> val r = s"""[$s]*(?:(.*[^$s])[$s]*|$$)""".r
r: scala.util.matching.Regex = [undo]*(?:(.*[^undo])[undo]*|$)

scala> def f(x: String) = x match { case r(null) => "" case r(y) => y case z => z }
f: (x: String)String
like image 36
som-snytt Avatar answered Feb 16 '23 04:02

som-snytt