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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With