正则表达式匹配所有'(def。+?})'

时间:2016-01-18 12:41:14

标签: regex scala

模式(def.+?})匹配第一个Scala方法:

object defvaltest {
  println("Welcome to the Scala worksheet")       //> Welcome to the Scala worksheet

  val str = "object t extends App { def one = { } def two = { } //Examples one two }"
                                                  //> str  : String = object t extends App { def one = { } def two = { } //Example
                                                  //| s one two }

  val Pattern = "(def.+?})".r                     //> Pattern  : scala.util.matching.Regex = (def.+?})

  Pattern.findFirstIn(str).get                    //> res0: String = def one = { }

}

如何将所有Scala方法匹配为List [String] 所以代替了 res0: String = def one = { }

返回

res0: List[String] = List("def one = { }" , "def two = { }")

1 个答案:

答案 0 :(得分:2)

您正在寻找与findFirstIn匹配的一场比赛。要查找多个匹配项,您需要findAllIn

val str = "object t extends App { def one = { } def two = { } //Examples one two }"
val Pattern = "(def.+?})".r
val res  = Pattern.findAllIn(str)
res.foreach {m =>
    println(m)
}

the demo的输出:

def one = { }
def two = { }
相关问题