【问题标题】:Android Pattern matcher failed to detect a special characterAndroid 模式匹配器未能检测到特殊字符
【发布时间】: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 有什么问题吗?

【问题讨论】:

    标签: android regex


    【解决方案1】:

    我想通了,问题是模式的第一部分和最后一部分 [^\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()
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 2021-11-03
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      相关资源
      最近更新 更多