我有一个字符串列表和一个正则表达式模式。我想过滤列表中与正则表达式不匹配的项目。我正在使用以下似乎不起作用的代码:
val matching = token.filter(x => regex.pattern.matcher(x).matches)
其中 token 是字符串列表,regex 是我要匹配的模式
您的代码应该可以工作。你确定你的正则表达式是正确的吗?
val regex = "a.c".r
val tokens = List("abc", "axc", "abd", "azc")
tokens filter (x => regex.pattern.matcher(x).matches)
//result: List[String] = List(abc, axc, azc)
编辑:
给定您的正则表达式,确保以下示例符合您的期望:
val regex = """\b[b-df-hj-np-tv-z]*[aeiou]+[b-df-hj-np-tv-z]*\b""".r
regex.pattern.matcher("good").matches
//res3: Boolean = true
regex.pattern.matcher("no good deed").matches
//res4: Boolean = false
该matches
方法将尝试匹配整个字符串。
完整性的另一种选择:
val words = List("alpha", "bravo", "charlie", "alphie")
words.filter(_.matches("a.*"))
res0: List[java.lang.String] = List(alpha, alphie)
你有没有试过这样:
val list = List("abc","efg","")
val p = java.util.regex.Pattern.compile(".*")
val matching = list filter { p.matcher(_).matches }
我在使用 Scala 的 Regex 引擎时遇到的问题是它.matches
会尝试匹配整个字符串,而不是对每个可能的子字符串进行匹配。
在许多正则表达式引擎中,以下代码将评估为匹配项:
"alphie".match(/a/)
在 Scala 中,.matches
在这里使用会失败;它将尝试将“a”与整个字符串“alphie”进行匹配。但是,如果 Regex 是/a*/
,它会起作用,因为该*
字符将匹配零个或多个字符。
如果添加重复的正则表达式符号不是一个选项,该findAllIn
方法可能很有用:
val words = List("alpha", "bravo", "charlie", "alphie")
val regex = "a.".r
//returns a tuple with the list item that matched, plus the text that fit the regex
for {
word <- words
matches <- regex.findAllIn(word)
} yield (word,matches)
注意:findAllIn
如果字符串中有多个匹配项,则可能多次匹配特定字符串。