正则表示式是用于在数据中查找模式(或缺少模式)的字符串。可使用.r方法将任意字符串转化为正则表达式。
# 导入包 import scala.util.matching.Regex # 创建正则表达式 val numberPattern: Regex = "[0-9]".r # 匹配模式 numberPattern.findFirstMatchIn("awesomepassword") match { case Some(_) => println("Password OK") case None => println("Password must contain a number") }使用括号搜索正则表达式组
val keyValPattern: Regex = "([0-9a-zA-Z-#() ]+): ([0-9a-zA-Z-#()/. ]+)".r val input: String = """background-color: #A03300; |background-image: url(img/header100.png); |background-position: top center; |background-repeat: repeat-x; |background-size: 2160px 108px; |margin: 0; |height: 108px; |width: 100%;""".stripMargin for (patternMatch <- keyValPattern.findAllMatchIn(input)) println(s"key: ${patternMatch.group(1)} value: ${patternMatch.group(2)}")对象提取器是指具有unapply方法的对象。apply方法类似于构造器,通过参数创建对象,与之相反,unapply方法将对象恢复成参数。这经常用于模式匹配与局部函数。
import scala.util.Random object CustomerID { def apply(name: String) = s"$name--${Random.nextLong}" def unapply(customerID: String): Option[String] = { val stringArray: Array[String] = customerID.split("--") if (stringArray.tail.nonEmpty) Some(stringArray.head) else None } } # 使用apply方法 val customer1ID = CustomerID("Sukyoung") // Sukyoung--23098234908 # 使用unapply方法 customer1ID match { case CustomerID(name) => println(name) // prints Sukyoung case _ => println("Could not extract a CustomerID") }由于值定义可以使用模式引入新的变量,所以提取器可以用于初始化变量,在这种情形下,unapply方法提供值。
val customer2ID = CustomerID("Nico") val CustomerID(cc) = customer2ID println(cc)note:等价于val cc = CustomerID.unapply(customer2ID).get。
unapply的返回值类型可以有:
如果只是测试,返回Boolean。例如,case even()如果返回类型T的单独子值,返回Option[T]如果返回多个子值T1,……,Tn,将其分组为可选元组Option[(T1,……,Tn)]有时,提取的值的数量并不固定,希望可以根据输入返回任意数量的值。为了通过定义unapplySeq方法来实现这一目的,此方法返回一个Option[Seq[T]]。模式的常用例子包括使用case List(x, y, z)=>解构List,使用正则表达式,例如case r(name, remainingFields @ _*)=>解构字符串。