Search code examples
regexscala

Scala: Pattern match on regex


The task is to match the comma separator in expression, excluding cases, when comma after digit or space.

For such test cases regex must match the comma:

"a,b"
"a,b,c"
"a,b,c,d"
"a,b,c,d,e1,1"

And for such:

"ab"
"abc1,1"

must not to match.

In generally the number of separated by comma elements may be 8-10.

The regex on Scala code is

 private val ContainCommaSeparatorExcludingDigitBeforeComma = """^.*\\D\\s*,.*$""".r

In particular

  ^.*\\D\\s*,.*$

is working fine. I checked it in, for example, that service https://regex101.com

But my Scala code with pattern matching does not works.

    address match {
      case ContainCommaSeparatorExcludingDigitBeforeComma(_, _, _) => print("found")
      case _ => print("not found")
    }

What am I doing wrong?


Solution

    1. Removing the backslashes in the string
    2. Replacing ContainCommaSeparatorExcludingDigitBeforeComma(_, _, _) with ContainCommaSeparatorExcludingDigitBeforeComma() since there are no groups defined so nothing to destructure.
    object Main extends App {
      val ContainCommaSeparatorExcludingDigitBeforeComma = """^.*\D\s*,.*$""".r
    
      val inputs = List("a,b", "a,b,c", "a,b,c,d", "a,b,c,d,e1,1", "ab", "abc1,1")
    
      inputs.foreach { input =>
        input match {
          case ContainCommaSeparatorExcludingDigitBeforeComma() => println("found")
          case _ => println("not found")
        }
      }
    }
    

    And an example with groups & pattern matching if that's what you wanted (1 group, extracting the \D)

    object Main extends App {
      val ContainCommaSeparatorExcludingDigitBeforeComma = """^.*(\D)\s*,.*$""".r
    
      val inputs = List("a,b", "a,b,c", "a,b,c,d", "a,b,c,d,e1,1", "ab", "abc1,1")
    
      inputs.foreach { input =>
        input match {
          case ContainCommaSeparatorExcludingDigitBeforeComma(m) => println(s"found '$m'")
          case _ => println("not found")
        }
      }
    }