Scala Pattern Match之Regular Expressions正則表達式
Scala正則表達式,以下是正則表達式的定義和使用,this
scala> val regex="""([0-9]+)([a-z]+)""".r regex: scala.util.matching.Regex = ([0-9]+)([a-z]+) scala> val str = "1618lyx" str: String = 1618lyx scala> val regex(num,name) = str num: String = 1618 name: String = lyx
將匹配的結果賦值給num 和 name。spa
在構造Regex的時候使用到String類的r方法,咱們也能夠直接使用Regex類進行:scala
scala> import scala.util.matching._ import scala.util.matching._ scala> scala> val regex = new Regex("""([0-9]+)([a-z]+)""") regex: scala.util.matching.Regex = ([0-9]+)([a-z]+) scala> val regex(num, blog) = str num: String = 1618 blog: String = lyx scala>
下面來看一下正則表達式在模式匹配中的應用,code
//r 方法表示建立一個正則表達式 val BookExtractorRE = """Book:title=([^,]+),\s+author=(.+)""".r val MagazineExtractorRE = """Magazine:title=([^,]+),\s+issue=(.+)""".r val catalog = Seq( "Book:title=Programming Scala Second Edition,author=Dean Wampler", "Magazine:title=The New York,issue=January 2014", "Unknown:text=who put this here?" ) /** * BookExtractorRE 是一個正則表達式,能夠將匹配的字符串賦值給title,author * 在case部分就能夠取到匹配到的變量 * entry :表示沒有匹配的變量 * * 對於大量轉義字符及換行的字符串可使用三個雙引號 * 三個雙引號的字符串能夠將換行符輸出 */ for (item <- catalog) { item match { case BookExtractorRE(title, author) => println( s"""Book $title, written by $author""") case MagazineExtractorRE(title, issue) => println(s"""Magazine "title" ,issue $issue""") case entry => println(s"Unrecognized entry:$entry") } }
==========END==========blog