Scala - Matching on Regular Expressions Code Example

The code for Matching on Regular Expressions

val MobileExtractorREGX = """Book: title=([^,]+),\s+authors=(.+)""".r
val LaptopExtractorREGX = """Magazine: title=([^,]+),\s+issue=(.+)""".r

val catalog = List(
 "Mobile: company=Apple, model=iPhone12",
 "Laptop: company=Dell, price=35,000/-",
 "Mobile: company=Apple, model=iPhone13",
 "Laptop: company=Lenovo, price=33,333/-",
 "Tablet: text=No Information?"
)

for (item <- catalog) {
 item match {
 case MobileExtractorREGX(company, model) =>
 println("Mobile \"" + company + "\", written by " + model)
 case LaptopExtractorREGX(company, price) =>
 println("Laptop \"" + company + "\", price " + price)
 case entry => println("Unrecognized entry: " + entry)
 }
}

/*
Output:
Unrecognized entry: Mobile: company=Apple, model=iPhone12
Unrecognized entry: Laptop: company=Dell, price=35,000/-
Unrecognized entry: Mobile: company=Apple, model=iPhone13
Unrecognized entry: Laptop: company=Lenovo, price=33,333/-
Unrecognized entry: Tablet: text=No Information?
*/
Code by IncludeHelp, on August 8, 2022 01:33

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.