Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive pattern matching for strings

Tags:

scala

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.

like image 234
ZhekaKozlov Avatar asked Apr 16 '14 16:04

ZhekaKozlov


People also ask

How do you do case-insensitive string comparison?

Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function.

How do you match a word with a case-insensitive in regex?

The i modifier is used to perform case-insensitive matching. For example, the regular expression /The/gi means: uppercase letter T , followed by lowercase character h , followed by character e . And at the end of regular expression the i flag tells the regular expression engine to ignore the case.

Which will do case-insensitive comparison of string contents?

strcasecmp() — Case-insensitive string comparison.


2 Answers

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
like image 52
Andreas Neumann Avatar answered Sep 30 '22 17:09

Andreas Neumann


Easy solution:

val str = "string1"

str toUpperCase match (str) {
  case "STRING1" => ???
  case "STRING2" => ???
}
like image 29
Antonio Maria Sanchez Berrocal Avatar answered Sep 30 '22 18:09

Antonio Maria Sanchez Berrocal