我的要求是接受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。我创建的模式有什么问题吗?
我知道了,问题出在模式[^ \ s]的第一部分和最后一部分,指示它接受除空白以外的任何内容。
我已经以这种方式更改了模式,现在可以使用了。
fun String.isValidUserName(): Boolean {
val pattern = Pattern.compile(
"[a-zA-Z0-9\\-]{1}" +
"[a-zA-Z 0-9\\-]{0,50}" +
"[a-zA-Z0-9\\-]{1}"
)
return this.length in 3..50
&& pattern.matcher(this).matches()
}