Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
805 views
in Technique[技术] by (71.8m points)

php - PCRE2 Regex error escape sequence is invalid in character class

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])(?=.[dX])(?=(?:.[!@#$%^&()\-_=+{}[]|;:,.]){1,}).{8,}$/

The error in the log is:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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, 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...