Scala 检查字符串是否不包含特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19704787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:49:05  来源:igfitidea点击:

Scala check if string contains no special chars

regexscala

提问by MeiSign

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

回答by Ion Cojocaru

This uses the Java string:

这使用 Java 字符串:

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:

或者,如果您不想处理 Regex,则可以使用以下任一方法从 Scala 的 RichString 中受益:

word.forall(_.isLetterOrDigit)

or:

或者:

!word.exists(!_.isLetterOrDigit)

回答by Mark Lister

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

我使用了 Set,这是逻辑上正确的选择,但它也应该与 Vector 一起使用,这样可以避免您看到混乱的字母...

回答by Ashalynd

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