user1269298
user1269298

Reputation: 737

scala - regular expression

I am new to scala. I am not new to regular expression, but scala's regular expression is a bit confusing to me. For example, my input variable is string from the "DEVICE" column

enter image description here

I would like to convert input with name from upper group to "TABLET", from middle group to "DESKTOP", and rest to "PHONE", like following. What is most elegant way to do it?

"IOSTABLET" => "TABLET"
"ANDROIDTABLET" => "TABLET"
"TABLET"  => "TABLET"
"SAFARI" => "DESKTOP"
...

Here is my solution using pattern matching

val tablet = """.*(TABLET)$""".r
val phone = """.*(PHONE)$""".r


"IOSTABLET" match {
  case tablet(device) => "TABLET"
  case phone(device) => "PHONE"
  case _ => "DESKTOP"
}

Upvotes: 0

Views: 49

Answers (1)

Ren
Ren

Reputation: 3455

val myDevice = "IOSTABLET"

val translated = myDevice match {
   case "IOSTABLET" | "ANDROIDTABLET" | "TABLET" => "TABLET"
   case "SAFARI" | "IE" => "DESKTOP"
   case "etc" | "etc2" => "etc3"
}

Something like that is probably the cleanest approach. You can use a regex but its probably not warranted here.

Upvotes: 2

Related Questions