douchao1864
2016-10-22 15:59
浏览 20
已采纳

是否可以在单个regexp中执行所有这些字符串验证?

I'm trying to figure out if I can combine all these statements into a single regexp check, but not being particularly well versed in regex doing it in these separate checks is the best I've got so far:

func ValidatePwd(pwd string) error {
    pwdRuneCount := utf8.RuneCountInString(pwd)
    containsAtLeastOneDigit, err := regexp.MatchString("[0-9]", pwd)
    if err != nil {
        return err
    }
    containsAtLeastOneLowercase, err := regexp.MatchString("[a-z]", pwd)
    if err != nil {
        return err
    }
    containsAtLeastOneUppercase, err := regexp.MatchString("[A-Z]", pwd)
    if err != nil {
        return err
    }
    containsAtLeastOneNonWordChar, err := regexp.MatchString(`[\W]`, pwd)
    if err != nil {
        return err
    }
    if pwdRuneCount < PwdMinRuneCount || pwdRuneCount > PwdMaxRuneCount || !containsAtLeastOneDigit || !containsAtLeastOneLowercase || !containsAtLeastOneUppercase || !containsAtLeastOneNonWordChar {
        return PwdErr
    }
    return nil
}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongsha1544 2016-10-22 19:36
    已采纳

    It's possible, but it would be ugly. A single regexp would have to contain 24 subexpressions of the form [0-9].*[a-z].*[A-Z].*\W to match each of the possible orders in which the four required character types could occur. The way you're doing it now is much better.

    By the way, instead of checking for errors from your MatchString calls (which means that the regular expression was invalid), you should probably precompile them with regexp.MustCompile, which panics if the regexp is invalid.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题