首页 > 解决方案 > 如何创建正则表达式以过滤掉关于长度、大小写和字符类别的复杂条件很少的结果

问题描述

我过滤了以下内容:

翻译为:

(?=.{2,}\d)(?=..*[a-z])(?=..*[A-Z]).{10,63}

然后我想排除一个以字母 u 开头并以三到六位数字结尾的单词:

([uU][0-9]{3,6})

但是,如何合并这两种模式来执行以下操作:

它不应该允许以下内容,因为它分别:

# does not have the required combination of characters
aaaaaaaaaaaaaaa

# is too long
asadsfdfs12BDFsdfsdfdsfsdfsdfdsfdsfdfsdfsdfsdfsdsfdfsdfsdfssdfdfsdfssdfdfsdfssdfdfsdfsdfsdfsdfsfdsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfs

# contains the pattern that shouldn't be allowed
U0000ABcd567890
ABcd56U00007890
D4gF3U432234
D4gF3u432234
ABcd567890U123456

应允许以下内容:

# it has the required combination of characters
ABcd5678990
ABcd567890

# does contain a part of the disallowed pattern (`([uU][0-9]{3,6})`), but does not fit that pattern entirely
ABcd567890U12
ABcd5U12abcdf
s3dU00sDdfgdg
ABcd56U007890

在此处创建和示例:https ://regex101.com/r/4b2Hu9/3

标签: javascriptregex

解决方案


在您的模式中,您使用了(?=..*\d)与您假设的含义不同的前瞻。

这意味着如果直接在右边的是任何字符的 2 倍或更多倍,除了换行符后跟一个数字,并且对于大写和小写变体相同。

您可以将模式更新为:

^(?!.*[uU]\d{3,6})(?=(?:\D*\d){2})(?=(?:[^a-z]*[a-z]){2})(?=(?:[^A-Z]*[A-Z]){2}).{10,63}$

在零件

  • ^字符串的开始
  • (?!.*[uU]\d{3,6})负前瞻,不断言uU后跟 3-6 位数字
  • (?=(?:\D*\d){2})断言 2 位数字
  • (?=(?:[^a-z]*[a-z]){2})断言 2 个小写字符
  • (?=(?:[^A-Z]*[A-Z]){2})断言 2 个大写字符
  • .{10,63}匹配除换行符以外的任何字符 10-63 次
  • $字符串结束

正则表达式演示


推荐阅读