Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Password validation with regexp

Tags:

regex

go

I am trying to write password validation function with regexp and don't know how to do it.

The regex package provided by the standard API of the Go language is different to other languages.

Have someone an idea, how this regexp pattern should looks like?

The pattern should validate:

/*
 * Password rules:
 * at least 7 letters
 * at least 1 number
 * at least 1 upper case
 * at least 1 special character
 */
like image 254
softshipper Avatar asked Sep 14 '14 19:09

softshipper


People also ask

What does ?= Mean in regular expression?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).


1 Answers

That's actually impossible since Go's regex doesn't support backtracking.

However, it's easy to implement, a simple example:

func verifyPassword(s string) (sevenOrMore, number, upper, special bool) {
    letters := 0
    for _, c := range s {
        switch {
        case unicode.IsNumber(c):
            number = true
        case unicode.IsUpper(c):
            upper = true
            letters++
        case unicode.IsPunct(c) || unicode.IsSymbol(c):
            special = true
        case unicode.IsLetter(c) || c == ' ':
            letters++
        default:
            //return false, false, false, false
        }
    }
    sevenOrMore = letters >= 7
    return
}
like image 111
OneOfOne Avatar answered Sep 20 '22 15:09

OneOfOne