如何匹配一个1位4个字母的字符串,其中一个字母重复两次,其余字母彼此不同

2024-04-19 00:27:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要正则表达式来匹配一个长度为5的单词,其中包含1个数字(0-9)和4个小写字母(a-z),但其中一个字母恰好重复了两次,其余的字母彼此不同。你知道吗

正确的匹配示例:

aa1bc  
2adba  
v4alv  

错误匹配示例:

aa1bbc   => notice that although one letter (a) repeat twice,
            other letters are not different from each other (bb)  
1aaaa  
b3ksl  

我使用^(?=.{5}$)[a-z]*(?:\d[a-z]*)(.*(.).*\1){1}$匹配所有包含1个数字和4个字母的单词,但我不知道如何确保只有一个字母重复两次,其余的字母则不同。你知道吗


Tags: 示例that错误字母数字单词onenotice
2条回答

保持dictionary以跟踪string的每个character的频率

(在线评论)

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)

试试下面的方法,你不需要正则表达式:

>>> import random,string
>>> l=random.sample(string.ascii_lowercase,4)
>>> l.append(str(random.randint(0,10)))
>>> random.shuffle(l)
>>> ''.join(l)
'iNx1k'
>>> 

或者想要更多:

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)

相关问题 更多 >