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
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)
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...
def containsNoSpecialChars(string: String) = string.matches("^[a-zA-Z0-9]*$")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With