Scala Character trimming strings

For any set of (final) characters, e.g.

val s = "un".toSet

how to trim a string using s, namely

"untidy stringnu".trimBy(s)
res: String = tidy string
+4
source share
2 answers

Scala has dropWhilewhich solves half the problem. It also has dropRightan analogue dropfor the right end of the collection. Unfortunately, he doesn’t dropWhileRight, so you need to be creative.

If you don’t really care about efficiency, you can just drop the characters from the left end, on the contrary, repeat and reverse:

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

If you are sure that this will be a bottleneck in your program (hint: maybe not), you need some imperative solution.

+5
source

. .

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

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
+3

Source: https://habr.com/ru/post/1542841/


All Articles