代码之家  ›  专栏  ›  技术社区  ›  E235

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

  •  -4
  • E235  · 技术社区  · 6 年前

    我需要正则表达式来匹配一个长度为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个字母的单词,但我不知道如何确保只有一个字母重复两次,其余的都不同。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Saketh Katari    6 年前

    保持 dictionary character string

    (注释内联)

    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)
    
        2
  •  0
  •   U13-Forward    6 年前

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

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