Regex match even number of letters

后端 未结 8 1102
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 05:35

I need to match an expression in Python with regular expressions that only matches even number of letter occurrences. For example:

AAA        # no match
AA                


        
8条回答
  •  无人及你
    2020-12-06 06:11

    'A*' means match any number of A's. Even 0.

    Here's how to match a string with an even number of a's, upper or lower:

    re.compile(r'''
        ^
        [^a]*
        (
            (
                a[^a]*
            ){2}
        # if there must be at least 2 (not just 0), change the
        # '*' on the following line to '+'
        )* 
        $
        ''',re.IGNORECASE|re.VERBOSE)
    

    You probably are using a as an example. If you want to match a specific character other than a, replace a with %s and then insert

    [...]
    $
    '''%( other_char, other_char, other_char )
    [...]
    

提交回复
热议问题