Android 模式匹配器无法检测到特殊字符



我的要求是接受 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()
}

最新更新