【问题标题】:Python Regex for number of times occurences of digit,alphabet用于数字、字母出现次数的 Python 正则表达式
【发布时间】:2020-03-05 20:52:26
【问题描述】:

我正在尝试编写一个正则表达式来验证令牌。

my token has a following structure:

  • 3 个或更多 [0-9] digits
  • 5 个或更多 [a-z] small alpha
  • 2 个或更多 [#@] special characters
  • 5 个或更多 [A-Z] upper alpha(可选?)可能存在或不存在。

注意:可选的 [A-Z] 字符可能存在于某些标记中,也可能不存在于某些标记中,当它存在于标记中时,它应该介于 5 or more 次之间。

  • 令牌长度与minimum of 6 to a max of 30 不同

有效/无效匹配的几个例子:

token1 : t4xa@ui13p#o6
breakdown : there are 7 [a-z] , 2 special chracter[@#] , 4 digits [0-9]
VALID MATCH: True

token2: 3@piy13Qx9#13@z1337
breakdown: there are 5 [a-z] , 3 special character [@#] , 10 digits [0-9] and 1 [A-Z](which is optional)
VALID MATCH: False (because `[A-Z]` exist in token but it exist for `1` time, it should exist atleast of 5 or more.)

token3: 3@piy1ABC3Qx9#13@DEGFz1337
breakdown: there are 5[a-z], 7 [A-Z] , 10 digits [0-9]
VALID MATCH: True
  • 到目前为止,我设法编写了一个正则表达式来验证至少一个数字、一个大写字母、至少一个小写字母、至少一个特殊字符。
^(?=.*[\d])(?=.*[A-Z])(?=.*[a-z])(?=.*[@#])[\w\d@#]{6,30}$

【问题讨论】:

  • 这部分5 or more [A-Z] upper alpha (optional ?) may exist or not是指0次还是5次或更多次?这是3@piy13Qx9#13@z1337 是有效还是无效匹配?
  • 感谢您的回复,是的,[A-Z] 再过 0 次或 5 次,是的,这两个示例都是有效的匹配项。

标签: python regex python-3.x regex-lookarounds regex-negation


【解决方案1】:

如果还有 0 个或 5 个以上大写字符,那么您可以使用正向预测来断言没有大写字符或至少 5 次。

(?=(?:[^A-Z\s]*$|(?:[^A-Z\s]*[A-Z]){5})

您可以使用否定字符类和量词来检查最少出现次数。

^(?=(?:[^\d\s]*\d){3})(?=(?:[^a-z\s]*[a-z]){5})(?=(?:[^@#\s]*[@#]){2})(?=(?:[^A-Z\s]*$|(?:[^A-Z\s]*[A-Z]){5}))[\w\d@#]{6,30}$

Regex demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    相关资源
    最近更新 更多