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

问题描述 投票:0回答:1

我的要求是接受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。我创建的模式有什么问题吗?

android regex
1个回答
0
投票

我知道了,问题出在模式[^ \ 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()
}
© www.soinside.com 2019 - 2024. All rights reserved.