Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala check if string contains no special chars

Tags:

regex

scala

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
like image 749
MeiSign Avatar asked Oct 31 '13 11:10

MeiSign


3 Answers

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)
like image 140
Ion Cojocaru Avatar answered Oct 21 '22 06:10

Ion Cojocaru


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...

like image 20
Mark Lister Avatar answered Oct 21 '22 05:10

Mark Lister


def containsNoSpecialChars(string: String) = string.matches("^[a-zA-Z0-9]*$")
like image 23
Ashalynd Avatar answered Oct 21 '22 05:10

Ashalynd