Home > Software engineering >  How to check if a string only contains certain characters in scala
How to check if a string only contains certain characters in scala

Time:02-24

How to check whether a string only contains certain characters, say "a" and "b" in Scala? I found several resources online, they are using regex. For Scala, most of them talked about the findAllIn or findFirstIn function. But I would like to have something that returns true or false.

CodePudding user response:

val s: String = ???

s.forall("ab".contains)

forall checks whether a condition is true for all elements of a collection. So in this case it checks whether a condition is true for each character in s.

contains checks whether a string contains a character, so "ab".contains(x) checks whether x is either 'a' or 'b'.

  • Related