【问题标题】:Python 3 regex searching for repeating characters function is not workingPython 3 正则表达式搜索重复字符功能不起作用
【发布时间】:2019-05-06 00:32:44
【问题描述】:

我有一个简短的函数,应该在 python 3 中使用正则表达式验证 UID,限制是:

  1. 它必须正好有 10 个字符。
  2. 只允许使用字母数字字符
  3. 字符不得重复

除了实际的字符重复之外,我已经完成了前面的所有步骤。

我尝试过使用\1*,但我不知道它应该做什么,因为我对正则表达式和 python 不熟悉。

import re

n = int(input())

for _ in range(n):
    UID = input()
    if re.match(r"(?:[a-zA-Z0-9]){10}$", UID):
        print("Valid")
    else:
        print("Invalid")

如果输入是:

2
B1CD102354
B1CDEF2354

它应该输出以下内容:

Invalid
Valid

因为B1CD1023541 重复。

但没有重复字符部分,它会输出:

Valid
Valid

【问题讨论】:

  • 如果你不想搞乱环视和反向引用,你可以随时len(set(UID)) == len(UID)

标签: python regex python-3.x validation


【解决方案1】:

试试这个^(?!.*(.).*\1)[a-zA-Z0-9]{10}$

https://regex101.com/r/XeaaTR/1

 ^ 
 (?!                       # No repeating chars
      .* 
      ( . )                     # (1)
      .* \1 
 )
 [a-zA-Z0-9]{10}           # 10 alnum's
 $

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多