Vadim
Vadim

Reputation: 825

Improve code with checking element in array is digit

I want to check that each element in String is digit. Firstly, I split the String to an Array by a regexp [, ]+ expression and then I try to check each element by forall and isDigit.

object Test extends App {
  val st = "1, 434, 634, 8"

  st.split("[ ,]+") match {
    case arr if !arr.forall(_.forall(_.isDigit)) => println("not an array")
    case arr if arr.isEmpty                      => println("bad delimiter")
    case _                                       => println("success")
  }
}

How can I improve this code and !arr.forall(_.forall(_.isDigit))?

Upvotes: 1

Views: 74

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627101

Use matches that requires the string to fully match the pattern:

st.matches("""\d+(?:\s*,\s*\d+)*""")

See the Scala demo and the regex demo.

Details

  • In a triple quoted string literal, there is no need to double escape backslashes that are part of regex escapes
  • Anchors - ^ and $ - are implicit when the pattern is used with .matches
  • The regex means 1+ digits followed with 0 or more repetitions of a comma enclosed with 0 or more whitespaces and then 1+ digits.

Upvotes: 1

jwvh
jwvh

Reputation: 51271

I think it can be simplified while also making it a bit more robust.

val st = "1,434 , 634   , 8"  //a little messier but still valid

st.split(",").forall(" *\\d+ *".r.matches)  //res0: Boolean = true

I'm assuming strings like "1,,,434 , 634 2 , " should fail.

The regex can be put in a variable so that it is compiled only once.

val digits = " *\\d+ *".r
st.split(",").forall(digits.matches)

Upvotes: 1

Related Questions