【发布时间】:2019-12-02 01:01:11
【问题描述】:
我的要求是接受包含 3-50 个字符且只能包含字母数字、空格(仅限中间)和连字符的字符串输入。
这是我的测试用例
class TestInput {
@Test
fun testUsernameValidation() {
println("Testing Valid UserName")
val tests = arrayOf(
"HelL&",
"HelL&&",
"HelL+&^% w0rld~",
"hello-the|_++)_%re",
" Sample",
"sh",
"slugging-patternsSLUGGING-pattern",
"sipletext"
)
tests.forEach {
println("${it.isValidUserName()}\t$it")
}
}
}
还有我的扩展
fun String.isValidUserName(): Boolean {
val pattern = Pattern.compile(
"[^\\s]" +
"[a-zA-Z 0-9\\-]{0,50}" +
"[^\\s]" )
return this.length in 3..50
&& pattern.matcher(this).matches()
}
这个测试产生结果:
Testing Valid UserName
true HelL&
false HelL&&
false HelL+&^% w0rld~
false hello-the|_++)_%re
false Sample
false sh
true slugging-patternsSLUGGING-pattern
true sipletext
唯一的问题是第一个只包含 1 个特殊字符的字符串返回 true。我创建的 Pattern 有什么问题吗?
【问题讨论】: