赞
踩
- import scala.util.matching.Regex
- import scala.util.matching.Regex.Match
-
- /*
- ----------------------------------------------------------
- 匹配
- */
- val rtr = "^(\\w+)@([a-z0-9]{2,})\\.(com|cn|edu|org)$";
- val regex:Regex = rtr.r
- // 同 Java 的简单匹配
- val bool: Boolean = "12665473@qq.com".matches(rtr)
-
- /*
- ----------------------------------------------------------
- 查找:模式匹配,对象提取:【元组,样例类】
- */
- val tp3: (String, String, String) = "12665473@q.com" match {
- case regex(g1, g2, g3) => (g1, g2, g3)
- case _ => ("INVALID", "INVALID", "INVALID")
- }
-
- /*
- ----------------------------------------------------------
- 替换
- */
- val rtr = "(8\\d+)"
- val regex:Regex = rtr.r
- val content = "java:88,mysql:80,scala:69,spark:75"
- val replace1: String = regex.replaceFirstIn(content, "99")
- // 参二为函数 f:Matcher=>Option[String]
- val replace2: String = regex.replaceSomeIn(content, m => Some((m.group(1).toInt+10).toString))
- val replace3: String = regex.replaceAllIn(content, "99")
- // 参二为函数 f:Matcher=>String
- val replace4: String = regex.replaceAllIn(content, m => (m.group(1).toInt+10).toString))
-
- /*
- ----------------------------------------------------------
- 分组:必须添加 ()
- */
- val regexPart = "\\d+".r
- val cont = "112,334,453,229,4567"
- val name: Option[String] = regexPart.findFirstIn(cont) // Some(112)
- val it: Regex.MatchIterator = regexPart.findAllIn(cont) // 112 334 453 229 4567
-
- Regex.Match match = regexXxx.findXxxMatchInt(content:String)
- val groupContent = match.group(id:Int)
-
- val rtr = "(\\w+):(\\d+)"
- val regex:Regex = rtr.r
- val content = "java:88,mysql:80,scala:69,spark:75"
- val name: Regex.Match = regexPart.findFirstMatchIn(cont)
- val matches: Iterator[Regex.Match] = regex.findAllMatchIn(content)
- matches.foreach(m=>println(s"${m.group(1)} => ${m.group(2)}"))
-
- /*
- 练习一:使用正则表达式解析日志
- 现有如下日志信息,请使用Scala正则表达式解析如下信息
- 日志级别
- 日期
- 请求URI
-
- INFO 2016-07-25 requestURI:/c?app=0&p=1&did=18005472&industry=469&adid=31
- INFO 2016-07-26 requestURI:/c?app=0&p=2&did=18005473&industry=472&adid=31
- INFO 2016-07-27 requestURI:/c?app=0&p=1&did=18005474&industry=488&adid=32
- */
- /*
- 隐式转换
- 隐式参数:隐式传入
- 场景:多个函数共享同一个参数,选择柯里化,将最后一个列表设计为该共享参数的唯一参数,并将
- 该参数设置为 implicit
- implicit order:Ordering[Int] = Ordering.Int.reverse
- val sorted = Array(8,1,3,2,5).sorted(implicit order:Ording[Int])
- 隐式函数:隐式类型转换
- implicit def strToInt(str:String) = str.toInt
- val a:Int = "12"
- 隐式类:扩展
- 用implicit关键字修饰的类,扩展其主构造器唯一参数类型的功能
- 只能在类、Trait、对象(单例对象、包对象)内部定义
- 构造器只能携带一个非隐式参数
- 隐式类不能是 case class
- 在同一作用域内,不能有任何方法、成员或对象与隐式类同名
- 隐式类必须有主构造器且只有一个参数
- */
-
- // 字符串的方法扩展,而在 Java 中 String 是final的,无法扩展
- implicit class StrExt(str:String){
- def incr() = str.map(c=>(c+1).toChar)
- def isEmail = str.matches("\\w+@[a-z0-9]{2,10}\\.(com(.cn)?|cn|edu|org)")
- }
-
- val a:String = "12665473@qq.com"
- val incr: String = a.incr
- val isEmail: Boolean = a.isEmail
- /*
- Exception : compiling : try...catch...
- RuntimeTime : running : 用程序逻辑(分支结构)
- 外部资源:释放 finally : try(resource extends AutoClosable)
- void close() throws Exception;
- */
- try(
- // 此处声明并初始化的 AutoCloseable 资源会在使用完自动释放
- ){
- // 代码块(非异常代码不放)
- }catch(Exception ex){
- // 异常的捕获和处理
- }
-
- try{
- // 代码块(非异常代码不放)
- }catch(Exception ex){
- // 异常的捕获和处理
- }finally {
- // 释放资源
- }
-
- // 同 Java
- def divideThrow(a:Int,b:Int) = {
- if(b==0){
- throw new Exception("divide by zero")
- }
- a/b
- }
-
- // 同 Java + Optional
- def divideTry(a:Int,b:Int):Option[Int] = {
- try{
- Some(a/b)
- }catch {
- case e:ArithmeticException => None
- }
- }
-
- // scala 特有 Either[Left异常,Right正常]
- def divideEither(a:Int,b:Int): Either[String,Int] = {
- try{
- Right(a/b)
- }catch {
- case e:ArithmeticException => Left("divide by zero")
- }
- }
-
- // 案例
- val e: Either[String, Int] = divideEither(1, 2)
- val v = if(e.isLeft) e.left else e.right
-
- // 【推荐】
- import scala.util.control.Exception.{allCatch,failAsValue}
- // Option[V] => Some(V) : None
- // V v = if(opt.isEmpty) defaultValue else opt.get
- def divideOpt(a:Int,b:Int) = {
- allCatch.opt(a/b)
- }
- // Try[V] => Success(V) : Failure(Throwable)
- def divideWithTry(a:Int,b:Int) = {
- allCatch.withTry(a/b)
- }
- // Either[Throwable,V] => Right(V) : Left(Throwable)
- def divideEither(a:Int,b:Int) = {
- allCatch.either(a/b)
- }
- // 【推荐】参数1:异常类型,参数2:异常发生返回的值,参数3:正常返回的值
- def divideFail(a:Int,b:Int) = {
- failAsValue(classOf[ArithmeticException])(-1)(a/b)
- }
- case class Text(author:String,title:String,price:Float)
- class TextSon(level:String,
- override val author:String,
- override val title:String,
- override val price:Float)
- extends Text(author, title, price)
- {
- val _level:String = level
- override def toString() = s"TextSon{${super.toString}, ${_level}}"
- }
-
- // 提取类型信息
- val ci: Class[Text] = classOf[Text]
-
- val obj:Text = new TextSon("TOP","The Wild Roaring","张培元",86.32f)
- // 类型判断
- val isIns: Boolean = obj.isInstanceOf[TextSon]
- // 类型转换:转换不当会导致 ClassCastException
- val son: TextSon = obj.asInstanceOf[TextSon]
- val son: Option[TextSon] = allCatch.opt(obj.asInstanceOf[TextSon])
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。