Dexter
Dexter

Reputation: 1409

Scala - match on regex for non-empty string

In Scala - I need to validate if a given string is non-empty. Following snippet returns true. What is the issue with the regex along with match?

  def isEmpty(input: String): String = {
    val nonEmptyStringPattern = raw"""(\w+)""".r
    input match {
      case nonEmptyStringPattern => s"matched $input"
      case _ => "n/a"
    }
  }

However, the same regex works are expected on matches method as below.


   def isEmpty(input: String): String = {
    val nonEmptyStringPattern = raw"""(\w+)""".r
    input match {
      case input if nonEmptyStringPattern matches( input) => s"matched $input"
      case _ => "n/a" ```.  
    }
  }

Does this mean match cannot have regex instances ?

Upvotes: 0

Views: 532

Answers (1)

jwvh
jwvh

Reputation: 51271

Just as case x => ... creates a new variable x to match against, it's the same for case nonEmptyStringPattern => .... A new variable is created that shadows the existing nonEmptyStringPattern. And as it's an unencumbered variable, it will match anything and everything.

Also, you've created and compiled a regex pattern but you have to invoke it in order to pattern match against it.

def isEmpty(input: String): String = {
  val nonEmptyStringPattern = "\\w+".r
  input match {
    case nonEmptyStringPattern() => s"matched $input"
    case _ => "n/a"
  }
}

This now works, except for the fact that not all String characters are \w word characters.

isEmpty("")     //res0: String = n/a
isEmpty("abc")  //res1: String = matched abc
isEmpty("#$#")  //res2: String = n/a

Upvotes: 4

Related Questions