I am writing a regular expression for password validation with the following code:
func IsPasswordValid(value string) bool {
pattern := regexp.MustCompile(`^.*(?=.{7,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).*$`)
return pattern.MatchString(value)
}
When I execute the application, it panics:
Line 45: - regexp: Compile(`^.*(?=.{7,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).*$`): error parsing regexp: invalid or unsupported Perl syntax: `(?=`
This regular expression works in Javascript and Ruby but not in Go. What I am do wrong here?
From the docs:
The syntax of the regular expressions accepted is the same general syntax used by Perl, Python, and other languages. More precisely, it is the syntax accepted by RE2 and described at http://code.google.com/p/re2/wiki/Syntax, except for \C.
The RE2 wiki clearly states:
(?=re) before text matching re (NOT SUPPORTED)
See also:
EDIT: if you really need PCRE features, you can use a binding package, e.g. https://github.com/tuxychandru/golang-pkg-pcre/. Otherwise, try to rethink your regexp and what it should match.
Golang's Regexp syntax is different from PCRE's (which php / javascript uses for the most part).
From https://code.google.com/p/re2/wiki/Syntax:
(?=re)
before text matching re (NOT SUPPORTED)
//edit
Example of checking the password without RE:
var ErrInvalidPassword = errors.New(`The password should at least have 7 letters, at least 1 number, at least 1 upper case, at least 1 special character.`)
func VerifyPassword(pw string) error {
if len(pw) < 10 {
return ErrInvalidPassword
}
var num, lower, upper, spec bool
for _, r := range pw {
switch {
case unicode.IsDigit(r):
num = true
case unicode.IsUpper(r):
upper = true
case unicode.IsLower(r):
lower = true
case unicode.IsSymbol(r), unicode.IsPunct(r):
spec = true
}
}
if num && lower && upper && spec {
return nil
}
return ErrInvalidPassword
}