使用正则表达式和POSIX字符类验证R中的密码

时间:2016-11-30 20:56:49

标签: r regex posix

我尝试使用regex和POSIX字符类在R中验证密码。我知道相当数量的正则表达式而不是POSIX作品。在询问正则表达式问题时,我查询了SO资源,加上了六个SO问题和答案,例如thisthat。密码的规则是:

  • 一个大写字母
  • 一个小写字母
  • 一个或多个特殊字符(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

我意识到即使结果显示&#34;有效&#34;,代码也无法正常工作。有人可以提供帮助吗? TY

2 个答案:

答案 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