【发布时间】:2018-05-26 10:41:40
【问题描述】:
我有一些存储在变量中的正则表达式和一个匹配操作,它根据匹配的模式返回一个字符串(如下所示)。我想将这些变量转换成一个数组或一个正则表达式列表,这样它们就可以被索引,我可以得到相应的组并返回适当的结果。
现有代码:
def parseString(str : String) : String = {
val ptrn2 = """/foo/bar/find/(apple|orange)/(\w+)$""".r
val ptrn3 = """/foo/bar/(fruit|vegetable)/(banana|carrot)/(\w+)$""".r
val ptrn4 = """/foo/bar/(volume|size)/(\d+)/(\d+)/(\d+)$""".r
// more variables
val response = str match {
case ptrn2(a,b) => "/foo/bar/"+ a +"/{id}"
case ptrn3(a,b,c) => "/foo/bar/"+ a +"/" + b + "/{ref}"
case ptrn4(a,b,c,d) => "/foo/bar/"+ a +"/" + (b.toInt*c.toInt*d.toInt)
// more case statements
case _ => str
}
return response
}
我尝试使用以下语法访问特定索引,传递变量来获取组,但这是不正确的。这有什么问题?
val prtn : List[Regex] = List(new Regex("regex here"),
new Regex("regex2 here"),
new Regex("regex3 here"))
val response = str match {
case ptrn(0)(a,b) => "/foo/bar/"+ a +"/{id}"
case ptrn(1)(a,b,c) => "/foo/bar/"+ a +"/" + b + "/{ref}"
case ptrn(2)(a,b,c,d) => "/foo/bar/"+ a +"/" + (b.toInt*c.toInt*d.toInt)
case _ => str
}
必须有一种方法可以通过匹配块中的 Arrays/List 访问它,或者如果 Map 返回适当的结果会更好。有谁知道如何在 Scala 中解决这个问题?
【问题讨论】:
标签: regex scala list pattern-matching