Reputation: 19
I have a list with Strings. For example: 10001_20180101010101_SOURCE_Text
I want to make an if statement for all of the strings such as if the ID from the first String is greater than the ID from the second String then print("anything")
and so on.
I tried with pattern matching like this:
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")
}
Can I somehow access id, year, month...?
Upvotes: 0
Views: 264
Reputation: 15455
I have a list with Strings. For example: "10001_20180101010101_SOURCE_Text" I want to make a if statement for all of the strings... if the ID from the first String is greater than the ID from the second String then print("anything") and so on.
Something like this?
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")
Upvotes: 3