我尝试使用regex和POSIX字符类在R中验证密码。我知道相当数量的正则表达式而不是POSIX作品。在询问正则表达式问题时,我查询了SO资源,加上了六个SO问题和答案,例如this和that。密码的规则是:
我已经尝试了许多代码变体,正如已注释掉的代码所示。我开始在较低级别构建正则表达式然后继续前进到应该包含所有要求的正则表达式。
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
我意识到即使结果显示&#34;有效&#34;,代码也无法正常工作。有人可以提供帮助吗? TY
答案 0 :(得分:1)
我更喜欢可读的逻辑而非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
答案 1 :(得分:1)
您可以使用以下正则表达式来验证:
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