【发布时间】:2016-11-15 12:56:26
【问题描述】:
我想扫描一个文件,只找到一个正则表达式的第一个实例,然后返回与该表达式匹配的组的值。
到目前为止,我的所有尝试似乎都非常笨拙,并且涉及重复使用正则表达式,一次是查找目标字符串,然后是再次获取组。我也不喜欢在 Regexp 的开头和结尾使用 .*。
任何人都可以提出一种更优雅的方式来做到这一点。
val DateRegexp = """.*(\d\d\d\d)-(\d\d)-(\d\d).*""".r
val lineWithDate = scala.io.Source.fromFile(filenameGC).getLines().find{_.matches(""".*(\d\d\d\d)-(\d\d)-(\d\d).*""") }
lineWithDate match {
case Some(result) =>
result match {
case DateRegexp(year, month, day) =>
println(year, month, day)
}
case None =>
println("No date found in file")
}
在得到 Cyrille Corpet 的大力支持后,我现在...
val DateRegexp = """(\d\d\d\d)-(\d\d)-(\d\d)""".r.unanchored
scala.io.Source.fromFile(filenameGC).getLines().collectFirst{
case DateRegexp(y, m, d) => println(y, m, d)}
【问题讨论】: