PCRE2 Regex error escape sequence is invalid in character class

Viewed 514

I have the following regex expression, for whatever reason I keep getting an error when using this with PCRE2. I'm unsure what would be causing the error.

/^.(?=.{1,})(?=.[A-Z])(?=.[0-9])(?=.[\d\X])(?=(?:.[!@#$%^&()\\\-_=\+{}[\]|;:,.]){1,}).{8,}$/

The error in the log is:

exception: preg_match(): Compilation failed: escape sequence is invalid in character class at offset 43

1 Answers

As per this Red Hat Bugzilla bug, this is a documented PCRE2 behavior:

Escape sequences in character classes

All the sequences that define a single character value can be used both inside and outside character classes. In addition, inside a character class, \b is interpreted as the backspace character (hex 08).

When not followed by an opening brace, \N is not allowed in a character class. \B, \R, and \X are not special inside a character class. Like other unrecognized alphabetic escape sequences, they cause an error. Outside a character class, these sequences have different meanings.

To fix your regex, I'd suggest something like

if (preg_match('/^(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&()\\\\_=+{}[\]|;:,.-]).{8,}$/', 'aB9!ssssddssdd')){
    echo "yes";
}

where

  • ^ - start of string
  • (?=.*[A-Z]) - at least one uppercase ASCII letter
  • (?=.*[a-z]) - at least one lowercase ASCII letter
  • (?=.*[0-9]) - at least one ASCII digit
  • (?=.*[!@#$%^&()\\\\_=+{}[\]|;:,.-]) - at least one special char, !, @, #, $, %, ^, &, (, ), \, _, =, +, {, }, [, ], |, ;, :, ,, . and -
  • .{8,} - at least 8 chars, no line breaks
  • $ - end of string.
Related