我有一个字符串,说var str = "hello, world"
和List
Regex
个模式
val patterns = List(new Regex("hello, (.*)", "substr"), new Regex("hi, (.*)", "substr"))
如何将str
与这些模式相匹配?现在,我没有使用List
模式,而是执行以下操作:
val pattern1 = new Regex("hello, (.*)", "substr")
val pattern2 = new Regex("hi, (.*)", "substr")
var someVar = "something"
var someVar2 = "something else"
str match {
case pattern1(substr) => { someVar = substr; someVar2 = "someValue" }
case pattern2(substr) => { someVar = substr; someVar2 = "someOtherValue" }
}
附录:
我忘了提一件重要的事情:实际上有几个模式列表。并且someVar2取决于发生第一个模式匹配的列表而取其值。对我来说,使用List(List(new Regex(...), new Regex(...), ...), List(new Regex(...), new Regex(...), ...))
等嵌套列表或对val
等每个模式列表使用单独的val patterns1 = List(new Regex(...), ...); val patterns2 = List(new Regex(...), ...)
无关紧要。
答案 0 :(得分:7)
试试这个:
scala> patterns.collectFirst{ p => str match { case p(substr) => substr } }
res3: Option[String] = Some(world)
scala> val str2 = "hi, Fred"
str2: String = hi, Fred
scala> patterns.collectFirst{ p => str2 match { case p(substr) => substr } }
res4: Option[String] = Some(Fred)
编辑:更新以考虑更改的要求......
假设:
val patternMapping = Map(("marker1" -> patterns), ("marker2" -> patterns2), ...)
您应该能够嵌套collectFirst调用,结果如下:
scala> patternMapping.collectFirst{ case (mark, pList) => pList.collectFirst{ p => str match { case p(substr) => (mark -> substr) } } }.flatten
res5: Option[(String, String)] = Some((marker1,world))
我怀疑这可能会被玩弄和整理,但应该给出一般的想法。
答案 1 :(得分:3)
嗯,你自己解决了。有很多方法。一种惯用的方式是:
val patterns = List(new Regex("hello, (.*)", "substr"), new Regex("hi, (.*)", "substr"))
patterns.foreach{ x =>
str match {
case x(substr) => { someVar = substr; someVar2 = "defaultValue" }
case _ => ;
}
}
如果您希望将defaultValue
替换为匹配的正则表达式索引,那么:
val i = patterns.zipWithIndex
i.foreach{ x =>
str match {
case x._1(substr) => { someVar = substr; someVar2 = "defaultValue - "+x._2 }
case _ => ;
}
}