Scala 正则表达式在以下两种情况下都可以很好地工作:
无条件执行的代码:例如
val lineregx = """([\w]+)\t([/\w.+-]+)\t([/\w+=\-!%# ]+)""".r
val anotherregx = """([\w]+)\t([/\w+=\-!%# ]+)""".r
val lineregx(category, aaUrl, title)
或者如果在 case 语句中我们使用表达式(并且不再需要它们..)
val lineregx = """([\w]+)\t([/\w.+-]+)\t([/\w+=\-!%# ]+)""".r
line match {
case lineregx(category, aaUrl, title) => // do something with category, aaUrl and title in here!
case anotherRegx(category, aaUrl) => // do something different with category, aaUrl and title in here!
case _ => { println("did not match line %s".format(line)); return 0 }
}
但是,如果我需要将匹配项“显示”到 case 语句之外的变量呢?特别是下面显示的var,
val lineregx = """([\w]+)\t([/\w.+-]+)\t([/\w+=\-!%# ]+)""".r
var category = "" ; var aaUrl = "";var title = ""
line match {
case lineregx(category, aaUrl, title) => val lineregx(category, aaUrl, title) = line
case anotherRegx(category, aaUrl) => val lineregx(category, aaUrl) = line
case _ => { println("did not match line %s".format(line)); return 0 }
}
// Do something with category, aaUrl, title HERE after the case statement.
问题是,应用 lineregx/anotherregex 的语法使这些变量仅对 case 语句是局部的。