我正在尝试使用REGEX和POSIX字符类在R中验证密码。我知道相当数量的正则是posix件。在提出正则问题时,我查找了SO资源,再加上六个问题,所以问题和答案,例如这个问题。密码的规则是:
- 一个大写字母
- 一个小写字母
- 一个或多个特殊字符(ASCII标点符号)
- 在8至32个字符之间
- ASCII可见和空间字符
我尝试了许多代码变化,如评论的代码所见。我开始在较低级别建造正则义务,然后延长了应包括所有要求的正则义务。
ValidatePassword <- function(stringChar) {
# validPW <- "([[:lower:]]+[[:upper:]]+){8,32}"
# validPW <- "[[:lower:]]+[[:upper:]]+"
# validPW <- "^(?=.*[[:lower:]])(?=.*[[:upper:]])(?=.*[[:punct:]])[[:print:]]{8,32}$"
# validPW <- "^(?:[[:lower:]])(?:[[:upper:]])(?:[[:punct:]])[[:print:]]{8,32}$"
# validPW <- "^(?:.*[[:lower:]])(?:.*[[:upper:]])(?:.*[[:punct:]])[[:print:]]{8,32}$"
# validPW <- "^([[:lower:]]+|[[:upper:]]+|[[:punct:]]+)[[:print:]]{8,32}$"
# validPW <- "^(?=.*[a-z])(?=.*[A-Z])(?=.*[[:punct:]])[[:print:]]{8,32}$"
# validPW <- "^([[:lower:][:upper:][:punct:]])[[:print:]]{8,32}"
validPW <- "^([[:lower:]]+|[[:upper:]]+|[[:punct:]]+)[[:print:]]{8,32}$"
return(length(grep(validPW, stringChar, value = TRUE)))
}
ifelse(ValidatePassword("#Password"), "valid", "not valid") # valid
ifelse(ValidatePassword("_PASSWORD"), "valid", "not valid") # not valid
ifelse(ValidatePassword("Password"), "valid", "not valid") # not valid
ifelse(ValidatePassword("password"), "valid", "not valid") # not valid
ifelse(ValidatePassword("passwor"), "valid", "not valid") # not valid
ifelse(ValidatePassword("pAsswords"), "valid", "not valid") # not valid
ifelse(ValidatePassword("Pa&sword"), "valid", "not valid") # valid
ifelse(ValidatePassword("Pa&s word"), "valid", "not valid") # valid
我意识到,即使结果为"有效",代码也无法正常工作。有人可以提供帮助吗?ty
您可以使用以下正则表达式来验证:
is.validpw <- function(x) {
grepl('(?x) # free-spacing mode
^ # assert position = beginning of string
(?=.*[[:upper:]]) # match one uppercase letter
(?=.*[[:lower:]]) # match one lowercase letter
(?=.*[[:punct:]]) # match one special character
[ -~]{8,32} # match printable ascii characters
$ # assert position = end of string', x, perl = TRUE)
}
is.validpw(c('#Password', '_PASSWORD', 'Password', 'password',
'passwor', 'pAsswords', 'Pa&sword', 'Pa&s word'))
## [1] TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
我倾向于更喜欢可读的逻辑,而不是L33T Regex-fu,因此其他人(或一个人的未来自我)可以掌握正在发生的事情。
is_valid_password <- function(x) {
grepl('((?=.*[[:lower:]])(?=.*[[:upper:]])(?=.*[[:punct:]]).{8,32})', x, perl=TRUE) &
grepl("[[:print:][:space:]]", x)
}
pwds <- c("#Password", "_PASSWORD", "Password", "password", "passwor", "pAsswords", "Pa&sword", "Pa&s word")
is_valid_password(pwds)
## [1] TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE