[英]How to match a strings with 1 digit and 4 letters that one letter repeat exactly twice and the rest different from each other
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.我需要正则表达式来匹配长度为 5 的单词,该单词包含 1 位数字( 0-9
)和 4 个小写字母( az
),但其中一个字母恰好重复两次,其余字母彼此不同。
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.我用^(?=.{5}$)[az]*(?:\\d[az]*)(.*(.).*\\1){1}$
来匹配所有包含 1 位数字的单词和 4 个字母,但我不知道如何确保只有一个字母重复两次,其余字母不同。
Maintain a dictionary
to keep track of frequencies of each character
of the string
维护dictionary
以跟踪string
中每个character
的频率
(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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.