Reputation: 53786
To remove characters from a List of Strings I use :
val validLines : List[String] = List("test[" , "test]")
val charsToClean: List[String] = List("\"", "[", "]", "'")
val filtered = validLines.map(line => line.replace(charsToClean(0), "")
.replace(charsToClean(1), "")
.replace(charsToClean(2), "")
.replace(charsToClean(3), ""))
I'm attempting use a inner map function instead of hard coding the positions of the chars to replace :
val filtered1 : List[String] = validLines.map(line => charsToClean.map {c => line.replace(c , "") })
But receive compiler error :
mismatch; found : List[List[String]] required: List[String]
Should result of line.replace(c , "")
not be returned ?
Upvotes: 4
Views: 3393
Reputation: 62835
No, because your code is more like: for every string and for every unwanted char, return replacement for this very symbol (n^2 strings).
What you probably wanted to do can be achieved using the following snippet:
val rawLines : List[String] = List("test[" , "test]")
val blacklist: Set[Char] = Set('\"', '[', ']' ,''')
rawLines.map(line => line.filterNot(c => blacklist.contains(c)))
// res2: List[String] = List(test, test)
Or alternatively, using regexp, as @ka4eli has shown in his answer.
Upvotes: 8
Reputation: 20405
Equivalent to @om-nom-nom though using a for comprehension syntax; given a set of characters to erase,
val charsToClean = """"[]'""".toSet
then
for (l <- validLines) yield l.filterNot(charsToClean)
where implicit set inclusion Char => Boolean
function is applied in filterNot
.
Upvotes: 1
Reputation: 5756
You need to use foldLeft
instead of map
.
val validLines : List[String] = List("test[" , "test]")
val charsToClean: List[String] = List("\"", "[", "]", "'")
val filtered : List[String] = validLines.map(line => charsToClean.foldLeft(line)(_.replace(_, "")))
Upvotes: 3
Reputation: 5424
replaceAll
can contain more complex regex constructed with |
(or) operator:
validLines.map(_.replaceAll("\\[|\\]|'|\"", ""))
Upvotes: 4