scala中的正则匹配和模式匹配

时间:2023-01-03 05:49:42

模式匹配:match case使用,这里其实使用了提取器



package kang

class Apple
case class RedApple(name:String, size:Int) extends Apple
case class GreenApple(name:String, size:Int) extends Apple

object Scala_PatternMatch {
def main(args: Array[String]): Unit = {
getSalary("java",4)
getParameterType(0.2)
getMatchCollection(Array("java"))
getAppleColor(RedApple("hong_1",4))
getAppleColor(GreenApple("lv_1",2))
getValue("java",Map("java"->"popular","scala"->"hot","hadoop"->"welcome"))

println("--")
//正则匹配
val pattern="[a-z]+"//加号是一个或多个,星号是零个或多个
val content="Hello! My Princess!"
println(pattern.matches(content))
val pattern2="[a-z]+".r
println(pattern2.findFirstIn(content))
println(pattern2.findAllIn(content))
println(pattern2.replaceFirstIn(content,"KANG"))
println(pattern2.replaceAllIn(content,"KANG"))
}


def getSalary(name: String, age: Int){
name match{
case "java" => println("120000")
case "scala" => println("150000")
case "spark" => println("110000")
case "hadoop" => println("140000")
case _ if(age<6) => println("unknowed")
case _name if(age<6) => println("name: "+_name+" salary: 134000")
case _ => println("unknowed ")
}
}


def getParameterType(msg: Any){
msg match{
case a:Int => println("Integer")
case b:String => println("String")
case c:Array[Int] => println("Array[Int]")
case d:Double => println("Double")
case _ => println("unknowed type")

}
}

def getMatchCollection(array: Array[String]){
array match{
case Array("java") => println("one")
case Array("java","scala") => println("two")
case Array("java","scala","spark") => println("three")
case Array("java", _*) => println("many")
case _ => println("unknowed collection")

}
}


def getAppleColor(apple: Apple){
apple match{
case RedApple(name, size) => println("RedApple-name: "+name +" size:"+size)
case GreenApple(name, size) => println("GreenApple-name: "+name +" size:"+size)
case _ => println("unknowed apple")
}
}

def getValue(key:String,content:Map[String,String]){
content.get(key) match{
case Some(value) => println("value: "+value)
case _ => println("unknowed key")

}

}
}