Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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")
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading