Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Pattern match on regex

Tags:

regex

scala

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?

like image 449
Jelly Avatar asked Feb 06 '26 21:02

Jelly


1 Answers

  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")
    }
  }
}
like image 97
Doot Avatar answered Feb 09 '26 10:02

Doot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!