1

I am a beginner in writing regex. I want to write a regex which matches only strings (alphanumeric) with unique characters (Does not match if even one char is repeated).

Example:

B1CDEF2354 -- Should match
B1CD102354 -- Should fail! because 1 repeats twice

Given the above two strings, it should only match the first string since all its characters are unique.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Karthik Bhandary
  • 1,305
  • 2
  • 7
  • 16

1 Answers1

3

Here is one approach, using a regex with a positive lookahead:

inp = "B1CDEF2354"
if re.search(r'^(?!.*(.).*\1)[A-Za-z0-9]+$', inp):
    print("MATCH")

Here is an explanation of the regex pattern:

^              from the start of the string
(?!.*(.).*\1)  assert that any single letter does NOT appear more than once
[A-Za-z0-9]+   then match one or more alphanumeric characters
$              end of the string
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360