Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Panic when compiling a regular expression

Tags:

regex

go

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?

like image 646
softshipper Avatar asked Sep 04 '26 12:09

softshipper


1 Answers

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:

  • http://golang.org/pkg/regexp/
  • https://code.google.com/p/re2/wiki/Syntax

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.

like image 143
Ainar-G Avatar answered Sep 07 '26 07:09

Ainar-G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!