【问题标题】:What's wrong with my regex for validating password?我的正则表达式验证密码有什么问题?
【发布时间】:2013-11-30 14:01:17
【问题描述】:

这是我验证密码的模式:

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

我使用函数preg_match 来验证

preg_match($pattern, $string);

但是当我运行它时,它显示了这个错误: Warning: preg_match(): Unknown modifier '\' in xxx on line 13

我的正则表达式有什么问题?

这里是正则表达式的解释: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)

【问题讨论】:

  • 您到底想“验证”什么?六个或更多非空格 ASCII 可打印字符的简单、直接的正则表达式是 [!-~]{6,},但你为什么不允许密码中的空格?

标签: php regex


【解决方案1】:

您需要两次转义正斜杠。有时您需要转义双斜杠的原因是它们被剥离了两次——一次由 PHP 引擎(在编译时),一次由正则表达式引擎。

来自PHP manual

单引号和双引号 PHP 字符串具有反斜杠的特殊含义。因此,如果 \ 必须与正则表达式 \ 匹配,则 PHP 代码中必须使用 "\\" 或 '\\'。

更新后的正则表达式应如下所示:

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

【讨论】:

  • 是的,我已经阅读了您的相同链接。我同意你的解决方案。
猜你喜欢
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 2011-05-06
  • 2016-10-19
  • 2011-03-24
  • 1970-01-01
相关资源
最近更新 更多