2

我有一个字符串,比如说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(...), ...))使用单独的列表都没有关系,比如.valval patterns1 = List(new Regex(...), ...); val patterns2 = List(new Regex(...), ...)

4

2 回答 2

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))

我怀疑这可能会被玩弄和整理,但应该给出一般的想法。

于 2013-08-27T14:16:11.133 回答
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 _ => ;     
           }
     }
于 2013-08-27T13:57:58.267 回答