模式匹配Scala,访问值

时间:2018-07-24 13:24:36

标签: scala pattern-matching

我有一个包含字符串的列表。例如:10001_20180101010101_SOURCE_Text

我想对所有字符串进行if语句,例如第一个字符串的ID大于第二个字符串的ID,然后是print("anything"),依此类推。

我尝试过这样的模式匹配:

val pattern = raw"([0-9]+)_(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})_(SOURCE|DEL)_(.*)".r
"some string" match {
  case pattern(id, year, month, day, hour, min, sec, typee, name: String) => 
    println(s"$id $year $month $day $hour $min $sec $typee $name")
  case _ => println("No match")
}

我可以以某种方式访问​​ID,年,月...吗?

1 个答案:

答案 0 :(得分:3)

  

我有一个包含字符串的列表。例如:“ 10001_20180101010101_SOURCE_Text”我想为所有字符串创建if语句...如果第一个字符串的ID大于第二个字符串的ID,则进行print(“ anything”),依此类推。

像这样吗?

case class Record(id: Int, year: Int, month: Int)

val pattern = raw"([0-9]+)_(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})_(TEXT|text|Text)_(.*)".r

def parse(record): Option[Record] =
  "some string" match {
    case pattern(id, year, month, day, hour, min, sec, typee, name: String) => 
      Some(Record(id, year, month))
      // println(s"$id $year $month $day $hour $min $sec $typee $name")
    case _ => None
      // println("No match")

val inputRecords: List[String] = ... // from input

val records: List[Record] = inputRecords.flatMap(parse)

if (records.get(0).id > records.get(1).id)
   print("anything")