I need regex to match a word with length of 5 that contains 1 digit ( 0-9
) and 4 small letters ( az
) but one of the letters repeat exactly twice and the rest are different from each other.
Example for correct match:
aa1bc
2adba
v4alv
Example for wrong match:
aa1bbc => notice that although one letter (a) repeat twice,
other letters are not different from each other (bb)
1aaaa
b3ksl
I used ^(?=.{5}$)[az]*(?:\\d[az]*)(.*(.).*\\1){1}$
to match all the words that contains 1 digit and 4 letters but I don't know how to make sure that only one letter repeat exactly twice and the rest are different.
Maintain a dictionary
to keep track of frequencies of each character
of the string
(comments inline)
def is_it_correct(inp):
if(len(inp) != 5):
return False
# store characters in a dictionary; key=ASCII of a character, value=it's frequency in the input string
ind = 0
dictionary = dict()
while(ind < len(inp)):
cur_char = inp[ind]
cur_int = ord(cur_char)
if(dictionary.get(cur_int) == None):
dictionary[cur_int] = 1
else:
dictionary[cur_int] = dictionary[cur_int]+1
ind = ind+1
# Make sure there's only one digit (0-9) i.e ASCII b/w 48 & 57
# Also, make sure that there are exactly 4 lower case alphabets (a-z) i.e ASCII b/w 97 & 122
digits = 0
alphabets = 0
for key, val in dictionary.items():
if(key >= 48 and key <= 57):
digits = digits+val
if(key >= 97 and key <= 122):
alphabets = alphabets+val
if(digits != 1 or alphabets != 4):
return False
# you should have 4 distinct ASCII values as your dictionary keys (only one ASCII is repeating in 5-length string)
if(len(dictionary) != 4):
return False
return True
ret = is_it_correct("b3ksl")
print(ret)
Try the below, you don't need regex for this:
>>> import random,string
>>> l=random.sample(string.ascii_lowercase,4)
>>> l.append(str(random.randint(0,10)))
>>> random.shuffle(l)
>>> ''.join(l)
'iNx1k'
>>>
Or if want more:
import random,string
lst=[]
for i in range(3):
l=random.sample(string.ascii_lowercase,4)
l.append(str(random.randint(0,10)))
random.shuffle(l)
lst.append(''.join(l))
import random,string
lst=[]
for i in range(3):
l=random.sample(string.ascii_lowercase,4)
l[-1]=l[0]
l.append(str(random.randint(0,10)))
random.shuffle(l)
lst.append(''.join(l))
print(lst)
import re
def check(val):
return len(set(val))!=len(val) and len(re.sub('\d+','',val)) and val.islower() and len(val)==5
a = check("a1abc")
print(a)
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.