【问题标题】:RegEx to match characters from list except if characters another list are present正则表达式匹配列表中的字符,除非存在另一个列表的字符
【发布时间】:2023-03-09 18:36:02
【问题描述】:

我正在尝试构建一个正则表达式来验证我的应用程序中的密码。

这是 PCRE (php)。

到目前为止,我的正则表达式看起来像这样

/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*\(\)_\+\-\=\[\]\{\}\|'])(?=.*[^\\\/])(?=.{8,20})/

我的标准如下

minimum length:            8
maximum length:            20
require special character: true
require uppercase:         true
require lowercase:         true
require number:            true
special character set:     !@#$%^&*()_+-=[]{}|'
excluded character set:    \/

除了排除的字符集外,一切正常。这个想法是密码不能包含该列表中指定的任何字符。

感谢您的帮助

【问题讨论】:

  • (?=.*[^\\\/]) 替换为(?!.*\/)。或者,删除此前瞻,并将 .{8,20} 替换为 [^\/]{8,20}

标签: php regex pcre


【解决方案1】:

使用

/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()_\-+=[\]{}|'])[^\/]{8,20}$/

proof

替代方案:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*()_\-+=[\]{}|'])[A-Za-z0-9!@#$%^&*()_+\-=[\]{}|']{8,20}$/

another proof

minimum length:            8                    <= {8,20}
maximum length:            20                   <= {8,20}
require special character: true                 <= (?=.*[!@#$%^&*()_\-+=[\]{}|'])
require uppercase:         true                 <= (?=.*[A-Z])
require lowercase:         true                 <= (?=.*[a-z])
require number:            true                 <= (?=.*[0-9])
special character set:     !@#$%^&*()_+-=[]{}|' <= [^\/]
excluded character set:    \/                   <= [^\/]

【讨论】:

  • 您的“替代方案”与您的第一个模式不同。在第一个模式中,[^/] 绝对允许所有非斜杠(包括控制字符、白色字符、缺少的标点字符和扩展的 ascii 部分\x80-\xFF),当“替代”模式将可能的字符限制为需要字符。
  • @CasimiretHippolyte 这就是我写“替代”而不是“等效”的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 2013-09-22
相关资源
最近更新 更多