MeiSign
MeiSign

Reputation: 1507

Scala check if string contains no special chars

I have written the following code to check whether a string contains special chars or not. The code looks too complicated to me but I have no idea how to make it simpler. Any Ideas?

def containsNoSpecialChars(string: String): Boolean = {
  val pattern = "^[a-zA-Z0-9]*$".r
  return pattern.findAllIn(string).mkString.length == string.length
}                                                 //> containsNoSpecialChars: (string: String)Boolean

containsNoSpecialChars("bl!a ")                   //> res0: Boolean = false
containsNoSpecialChars("bla9")                    //> res1: Boolean = true

Upvotes: 9

Views: 19045

Answers (3)

Ion Cojocaru
Ion Cojocaru

Reputation: 2583

This uses the Java string:

word.matches("^[a-zA-Z0-9]*$")

or if you do not want to deal with Regex one can benefit from Scala's RichString by using either:

word.forall(_.isLetterOrDigit)

or:

!word.exists(!_.isLetterOrDigit)

Upvotes: 18

Ashalynd
Ashalynd

Reputation: 12563

def containsNoSpecialChars(string: String) = string.matches("^[a-zA-Z0-9]*$")

Upvotes: 8

Mark Lister
Mark Lister

Reputation: 1143

scala> val ordinary=(('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9')).toSet
ordinary: scala.collection.immutable.Set[Char] = Set(E, e, X, s, x, 8, 4, n, 9, N, j, y, T, Y, t, J, u, U, f, F, A, a, 5, m, M, I, i, v, G, 6, 1, V, q, Q, L, b, g, B, l, P, p, 0, 2, C, H, c, W, h, 7, r, K, w, R, 3, k, O, D, Z, o, z, S, d)

scala> def isOrdinary(s:String)=s.forall(ordinary.contains(_))
isOrdinary: (s: String)Boolean


scala> isOrdinary("abc")
res4: Boolean = true

scala> isOrdinary("abc!")
res5: Boolean = false

I used a Set, the correct choice logically, but it should also work with a Vector which will avoid you looking at the jumbled letters...

Upvotes: 13

Related Questions