简体   繁体   中英

What's wrong with my regex for validating password?

Here is my pattern for validating password:

$pattern = '/^[0-9A-Za-z!@#$^%*_|;:\'"`~.,\(\)\{\}\[\]\<\>\\\/\?\-\+\=\&]{6,}$/m';

I use function preg_match to validate

preg_match($pattern, $string);

But when I run it, it shows this error: Warning: preg_match(): Unknown modifier '\\' in xxx on line 13

What's wrong with my regex?

Here is the regular expression explained: http://regex101.com/r/rR6uH0/

^ assert position at start of a line
[0-9A-Za-z!@#$^%*_|;:'"`~.,\(\)\{\}\[\]\<\>\\\/\?\-\+\=\&]{6,} match a single character present in the list below
Quantifier: Between 6 and unlimited times, as many times as possible, giving back as needed [greedy]
0-9 a single character in the range between 0 and 9
A-Z a single character in the range between A and Z (case sensitive)
a-z a single character in the range between a and z (case sensitive)
!@#$^%*_|;:'"`~., a single character in the list !@#$^%*_|;:'"`~., literally
\( matches the character ( literally
\) matches the character ) literally
\{ matches the character { literally
\} matches the character } literally
\[ matches the character [ literally
\] matches the character ] literally
\< matches the character < literally
\> matches the character > literally
\\ matches the character \ literally
\/ matches the character / literally
\? matches the character ? literally
\- matches the character - literally
\+ matches the character + literally
\= matches the character = literally
\& matches the character & literally
$ assert position at end of a line
g modifier: global. All matches (don't return on first match)
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

You need to escape the forward slashes twice. The reason why you sometimes need to escape double slashes is that they are stripped twice -- once by PHP engine (at compile time) and once by regular expression engine.

From the PHP manual :

Single and double quoted PHP strings have special meaning of backslash. Thus if \\ has to be matched with a regular expression \\, then "\\\\" or '\\\\' must be used in PHP code.

The updated regular expression should look like:

$pattern = '/^[0-9A-Za-z!@#$^%*_|;:\'"`~.,\(\)\{\}\[\]\<\>\\\\\/\?\-\+\=\&]{6,}$/m';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM