问题描述
尝试了几个小时才能使这个简单的验证生效.看来我尝试检查的结果都不一致.
Been trying for hours to get this simple validation to work.It seems whatever i try to check, results are inconsistent..
fun validatePassword(password: Password): Boolean {
val noUpper = "(?=.*[A-Z])".toRegex()
val noLower = "(?=.*[a-z])".toRegex()
val noDigit = "(?=.*\\d)".toRegex()
when {
!password.newPassword.matches(noUpper) -> {
throw WebApplicationException("Password missing uppercase letter")
}
!password.newPassword.matches(noLower) -> {
throw WebApplicationException("Password missing digit")
}
!password.newPassword.matches(noDigit) -> {
throw WebApplicationException("Password missing lowercase letter")
}
else -> return true
}
}
我对正则表达式不太满意.我该如何正确检查这里显示的错误?
Im not too good with regex..how do i get these to check properly agains the errors shown here?
谢谢
推荐答案
matches()
方法需要完整的字符串匹配,并且您的正则表达式仅匹配一个空位置,后跟除换行符以外的任何0+字符,后跟一个高位字符.或小写字母或数字.您需要匹配并使用整个字符串.
The matches()
method requires a full string match, and your regexps only match an empty location followed with any 0+ chars other than line break chars followed with either an upper- or lowercase letters or a digit. You need to match and consume the whole string.
一种解决方法是仅修改正则表达式并按原样使用其余代码:
One fix is to modify just the regexps and use the rest of code as is:
val noUpper = "(?s)[^A-Z]*[A-Z].*".toRegex()
val noLower = "(?s)[^a-z]*[a-z].*".toRegex()
val noDigit = "(?s)\\D*\\d.*".toRegex()
或者,使用 find()
(允许在更长的字符串内进行部分匹配),并使用一些更简单的正则表达式:
Or, use find()
(that allows partial matches inside longer strings) with a bit simpler regexes:
val noUpper = "[A-Z]".toRegex()
val noLower = "[a-z]".toRegex()
val noDigit = "\\d".toRegex()
然后
when {
noUpper.find(password) == null -> {
throw WebApplicationException("Password missing uppercase letter")
}
noLower.find(password) == null -> {
throw WebApplicationException("Password missing digit")
}
noDigit.find(password) == null -> {
throw WebApplicationException("Password missing lowercase letter")
}
else -> return true
}
这篇关于Kotlin,无法匹配正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!