我正在开发接收文本命令的应用程序:
例如文本命令play film ramboo first blood tv
。
首先,我需要测试命令匹配。然后,我需要从中提取参数:
media = film,
name = ramboo first blood
source = tv
为了进行匹配检查,我构建了正则表达式。
这是我的命令定义:
sealed trait WordLike {
def parameter: String
}
case class Word(parameter: String, variants: Set[String] = Set.empty) extends WordLike
case class Any(parameter: String) extends WordLike
case class CommandDef(sentence: List[WordLike]) {
private lazy val regexp = {
def acc(r: String, sentence: List[WordLike]): String = {
sentence match {
case x :: xs =>
x match {
case Word(p, variants) => acc(r + "(" + variants.mkString("|") + ")", xs)
case Any(p) => acc(r + ".*", xs)
}
case Nil => r
}
}
acc("^", sentence) + "$"
}
def `match`(text: String): Boolean = text.matches(regexp)
}
上面示例中的正则表达式:^(play)(film|song).*(tv|pc)$
我这样使用我的代码:
val cmd = CommandDef(List(
Word("play"),
Word("media", variants = Set("film", "music")),
Any("name"),
Word("source", variants = Set("tv", "pc"))))
cmd.`match`("play film ramboo first blood tv")
我不知道如何从文本中提取参数。
答案 0 :(得分:3)
捕获组可用于提取参数
val pattern = """^(play) (film|song) (.*) (tv|pc)$""".r("command", "media", "name", "source")
pattern.findFirstMatchIn("play film ramboo first blood tv").foreach { m =>
println(s"media = ${m.group("media")}")
println(s"name = ${m.group("name")}")
println(s"source = ${m.group("source")}")
输出:
media = film
name = ramboo first blood
source = tv
答案 1 :(得分:0)
@ olik1回答中的正则表达式很好,但是使用match
取消选择可能会更干净:
val CommmandPattern = """^(play) (film|song) (.*) (tv|pc)$""".r
def matchCommand(s: String) =
s match {
case CommmandPattern(command, media, name, source) =>
println(s"command=$command, nedia=$media, name=$name, source=$source")
case _ =>
println("Failed to parse command")
}
这会将匹配的值直接放入变量中,并允许进行清晰的错误处理。如果您想要更灵活的语法,还可以向match
添加多个模式。