在Golang中使用正则表达式确保特定的字符在字符串中,而不管位置如何

时间:2019-04-20 02:51:10

标签: regex go

我正在构建一个超级简单的功能,以确保密码包含特定字符。即,密码应具有以下内容:

  • 一个小写字母
  • 一个大写字母
  • 一位数字
  • 一个特殊字符
  • 没有空格,#|

我认为正则表达式将是执行此操作的最简单方法。但是,我很难弄清楚如何在Golang中做到这一点。当前,我有一堆单独的正则表达式MatchString函数,我将这些函数组合起来以获得所需的功能。例如:

lowercaseMatch := regexp.MustCompile(`[a-z]`).MatchString
uppercaseMatch := regexp.MustCompile(`[A-Z]`).MatchString
digitMatch := regexp.MustCompile(`\d`).MatchString
specialMatch := regexp.MustCompile(`\W`).MatchString
badCharsMatch := regexp.MustCompile(`[\s#|]`).MatchString
if (lowercaseMatch(pwd) 
        && uppercaseMatch(pwd) 
        && digitMatch(pwd)
        && specialMatch(pwd)
        && !badCharsMatch(pwd)) {
    /* password OK */
} else {
    /* password BAD */
}

尽管这使内容易于阅读,但我希望使用更简洁的正则表达式,但是我不知道如何获取正则表达式来搜索上述每个类别的单个字符(无论位置如何)。有人可以指出我正确的方向吗?此外,如果有比regex更好的方法,那么我会不知所措。

谢谢!

1 个答案:

答案 0 :(得分:2)

由于golang使用re2,因此它不支持正向超前(?= regex),因此我不确定是否有办法编写涵盖所有情况的正则表达式。

相反,您可以使用unicode软件包:

func verifyPassword(s string) bool {
    var hasNumber, hasUpperCase, hasLowercase, hasSpecial bool
    for _, c := range s {
        switch {
        case unicode.IsNumber(c):
            hasNumber = true
        case unicode.IsUpper(c):
            hasUpperCase = true
        case unicode.IsLower(c):
            hasLowercase = true
        case c == '#' || c == '|':
            return false
        case unicode.IsPunct(c) || unicode.IsSymbol(c):
            hasSpecial = true
        }
    }
    return hasNumber && hasUpperCase && hasLowercase && hasSpecial
}