Scala只提取某些字符

时间:2015-07-16 22:30:05

标签: regex scala

我在Scala中逐行接受字符串,我希望能够删除所有不属于任意字母S集合的字符。

我会做val模式= S.r吗?如何解析一行以删除不在S中的所有字符?

1 个答案:

答案 0 :(得分:0)

您可以使用filterNot删除集合中的任何字符。

scala> val vowels = Set("a","e","i","o","u")
vowels: scala.collection.immutable.Set[String] = Set(e, u, a, i, o)

scala> val line = """I am taking in line by line in Scala as a string, and I want to be able to remove all characters that don't belong to some arbitrary collection of letters S."""
line: String = I am taking in line by line in Scala as a string, and I want to be able to remove all characters that don't belong to some arbitrary collection of letters S.

scala> line.filterNot(x => vowels.contains(x.toString))
res4: String = I m tkng n ln by ln n Scl s  strng, nd I wnt t b bl t rmv ll chrctrs tht dn't blng t sm rbtrry cllctn f lttrs S.