简体   繁体   English

我的用于验证密码的正则表达式有什么问题?

[英]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进行验证

preg_match($pattern, $string);

But when I run it, it shows this error: Warning: preg_match(): Unknown modifier '\\' in xxx on line 13 但是,当我运行它时,它显示此错误: 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/ 这是解释的正则表达式: 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. 之所以有时需要转义双斜杠,是因为它们被剥离了两次,一次是由PHP引擎(在编译时),一次是由正则表达式引擎。

From the PHP manual : PHP手册

Single and double quoted PHP strings have special meaning of backslash. 单引号和双引号的PHP字符串具有反斜杠的特殊含义。 Thus if \\ has to be matched with a regular expression \\, then "\\\\" or '\\\\' must be used in PHP code. 因此,如果\\必须与正则表达式\\匹配,则在PHP代码中必须使用“ \\\\”或'\\\\'。

The updated regular expression should look like: 更新后的正则表达式应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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