ZhekaKozlov
ZhekaKozlov

Reputation: 39526

Case insensitive pattern matching for strings

match (str) {
  case "String1" => ???
  case "String2" => ???
}

This is case sensitive matching. How to write case insensitive matching? I know I can call toLowerCase for each branch, but I want more elegant solution.

Upvotes: 20

Views: 22295

Answers (3)

Easy solution:

val str = "string1"

str toUpperCase match (str) {
  case "STRING1" => ???
  case "STRING2" => ???
}

Upvotes: 8

pathikrit
pathikrit

Reputation: 33409

Another approach that does not depend on regexes or interpolaters:

 implicit class StringExtensions(val s: String) extends AnyVal {
    def insensitive = new {
      def unapply(other: String) = s.equalsIgnoreCase(other)
    }
  }

  val test1 = "Bye".insensitive
  val test2 = "HELLo".insensitive

  "Hello" match {
    case test1() => println("bad!")
    case test2() => println("sweet!")
    case _ => println("fail!")
  }

Here is another way using interpolaters but no regex:

  implicit class StringInterpolations(sc: StringContext) {
    def ci = new {
      def unapply(other: String) = sc.parts.mkString.equalsIgnoreCase(other)
    }
  }

  "Hello" match {
    case ci"Bye" => println("bad!")
    case ci"HELLO" => println("sweet!")
    case _ => println("fail!")
  }

The above can also be used to pattern match inside case classes e.g.:

case class Dog(name: String)

val fido = Dog("FIDO")

fido match {
  case Dog(ci"fido") => "woof"    
  case _ => "meow :("    
}

Upvotes: 7

Andreas Neumann
Andreas Neumann

Reputation: 10884

Basic approach:

You could use Pattern Guards and Regular Expressions

str match {
case s if s matches "(?i)String1" => 1
case s if s matches "(?i)String2" => 2
case _ => 0
}

Sophisticated method:

Implicits with String Interpolation and Regex

implicit class CaseInsensitiveRegex(sc: StringContext) {
  def ci = ( "(?i)" + sc.parts.mkString ).r
}

def doStringMatch(str: String) = str match {
  case ci"String1" => 1
  case ci"String2" => 2
  case _ => 0
}

Some example usage in the REPL:

scala> doStringMatch("StRINg1")
res5: Int = 1

scala> doStringMatch("sTring2")
res8: Int = 2

Upvotes: 28

Related Questions