Scala列表匹配正则表达式

pri*_*sia 6 regex scala list match

我有一个字符串列表和一个正则表达式模式.我想过滤列表中与正则表达式不匹配的项目.我使用以下代码似乎不起作用:

val matching = token.filter(x => regex.pattern.matcher(x).matches)
Run Code Online (Sandbox Code Playgroud)

其中token是字符串列表,regex是我想要匹配的模式

小智 9

你的代码应该有效.你确定你的正则表达式是正确的吗?

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)
Run Code Online (Sandbox Code Playgroud)

编辑:

鉴于您的正则表达式,请确保以下示例符合您的期望:

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
Run Code Online (Sandbox Code Playgroud)

matches方法将尝试匹配整个字符串.