0

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 ?

nashter
  • 1,181
  • 1
  • 15
  • 33

1 Answers1

4

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
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • Explanation "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." from @jwvh nails the answer. Took a while to understand that match creates a variable with case. However, I am yet to understand why an unencoutered variable match anything. – nashter Jan 05 '20 at 07:25
  • @jwvh: I think You need to pass `input` string here `case nonEmptyStringPattern(input) => s"matched $input"` otherwise it will always match with "n/a". – asanand Jan 05 '20 at 07:32
  • 2
    @asanand; I removed the capture group. As you can see from the test output, it will match one or more `\w` word characters. – jwvh Jan 05 '20 at 07:36
  • @jwvh: Ohh I missed that. Thanks – asanand Jan 05 '20 at 07:37
  • 1
    @dexter2305; `case x =>` creates the variable `x` that is _unencumbered_, i.e. unrestricted as to the values it can hold. In other words, there is no guard (`case x if ...`) or other condition that would cause the match to fail. – jwvh Jan 05 '20 at 07:42