简体   繁体   中英

Searching for capital letters in string using regular expressions

I am attempting to locate 3, 4, or 5 consecutive capital letters within a string. They can proceed a '$' or '(' but this is optional. Below is what I have that handles the capital letters but I haven't figure out how to check for letters proceeding a '$' or '('.

ex: ($ABC), (ABC), $ABC, ABC <---all should trigger

searches = [r'[A-Z]{5}', r'[A-Z]{4}', r'[A-Z]{3}']
correct = '$ABCD'

        for search in searches:
            confirmed = re.search(search, correct)
            if confirmed:
                return confirmed
            else:
                return False

    Process finished with exit code 0

A regex is overkill here, just use plain Python.

>>> correct = '$ABCD'
>>> any(correct[i:i+3].isupper() for i in range(0,len(correct)-3,3))
True
>>> correct = "AbCD"
>>> any(correct[i:i+3].isupper() for i in range(0,len(correct)-3,3))
False

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM