If your count
value should be 7
and the fruit
value should be 2323
, you can use
val pattern = "([1-7]),((?:[0-1][0-9]|2[0-3]){2})".r
val line = "7,2323"
val (count, fruit) = line match {
case pattern(count, fruit) => (count,fruit)
case _ => ("","")
}
println(s"${count} and ${fruit}")
// => 7 and 2323
See the Scala demo.
Note the ([1-7]),((?:[0-1][0-9]|2[0-3]){2})
refactored pattern that now contains only two capturing groups. pattern(count, fruit)
"extracts" the capturing group values and assigns them to count
and fruit
. If there is no match, these variable will be empty strings.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…