简体   繁体   中英

Python 3 regex searching for repeating characters function is not working

I have a short function that is supposed to validate a UID using regular expressions in python 3 and the restrictions are:

  1. It has to have exactly 10 characters.
  2. Only alphanumeric characters allowed
  3. No characters should repeat

I've done all the previous steps except for the actual character repeat.

I've tried using \\1* , and I had no idea what it was supposed to do because I am new to regular expressions and python in general.

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")

And if the input is:

2
B1CD102354
B1CDEF2354

It is supposed to output the following:

Invalid
Valid

Because B1CD102354 has 1 repeating.

But without the repeating characters part it outputs this:

Valid
Valid

Try this ^(?!.*(.).*\\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
 $

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM