val BookExtractorRE = """Book: title=([^,]+),/s+authors=(.+)""".r
val MagazineExtractorRE = """Magazine: title=([^,]+),/s+issue=(.+)""".r
val catalog = List(
"Book: title=Programming Scala, authors=Dean Wampler, Alex Payne",
"Magazine: title=The New Yorker, issue=January 2009",
"Book: title=War and Peace, authors=Leo Tolstoy",
"Magazine: title=The Atlantic, issue=February 2009",
"BadData: text=Who put this here??"
)
for (item <- catalog) {
item match {
case BookExtractorRE(title, authors) =>
println("Book /"" + title + "/", written by " + authors)
case MagazineExtractorRE(title, issue) =>
println("Magazine /"" + title + "/", issue " + issue)
case entry => println("Unrecognized entry: " + entry)
}
}
可以看出,case后面带一个文本串正则是很方便的。
以下是关于.r的解释
We start with two regular expressions, one for records of books and another for records of magazines. Calling .r on a string turns it into a regular expression; we use raw (triple-quoted) strings here to avoid having to double-escape backslashes. Should you find the .r transformation method on strings unclear, you can also define regexes by creating new instances of the Regex class, as in: new Regex("""/W""").