regexscalapattern-matching

Pattern matching against regex strange behaviour scala


Can someone explain to me why is this happening,

val p = """[0-1]""".r

"1" match { case p => print("ok")} 
//returns ok, Good result

"4dd" match { case p => print("ok")}
//returns ok, but why? 

I also tried:

"14dd" match { case p => print("ok") case _ => print("non")}
//returns ok with: warning: unreachable code

Solution

  • You'll find the answer if you try to add a new option:

    "4dd" match {
    case p => print("ok")
     case _ => print("ko")
    }
    
    <console>:24: warning: patterns after a variable pattern cannot match (SLS 8.1.1)
     "4dd" match { case p => print("ok"); case _ => print("ko")}
    

    You are matching against a pattern without extract any value, the most common use of regex is, afaik, to extract pieces of the input string. So you should define at least one extraction by surrounding it with parenthesis:

    val p = """([0-1])""".r
    

    And then match against each of the extraction groups:

    So this will return KO

    scala> "4dd" match {
         |     case p(item) => print("ok: " + item)
         |      case _ => print("ko")
         |     }
    ko
    

    And this will return OK: 1

    scala>  "1" match {
         |         case p(item) => print("ok: " + item)
         |          case _ => print("ko")
         |         }
    ok: 1