import timeit
stmt = """
import re
reg = '^(?:[A-Z0-9][A-Z0-9_]*)?[A-Z0-9]$'
p = re.compile(reg)
p.match('%s')
"""
str_list = ['MY_HERO2', 'MY_SUPER_GREAT_UNBELIEVABLE_HERO',
    'MY_SUPER_GREAT_UNBELIEVABLE HERO',
    'MY_SUPER_GREAT_UNBELIEVABLE_STRONG_HERO',
    'MY_SUPER_GREAT_UNBELIEVABLE_STRONG HERO']
for s in str_list:
    t = timeit.timeit(stmt % s, number=1000)
print('%s: %s' % (s, t))
import re
reg = '^(?:[A-Z0-9][A-Z0-9_]*)?[A-Z0-9]$'
p = re.compile(reg)
for s in str_list:
    result = p.match(s) is not None
print('%s: %s' % (s, result))
Python regex slow when whitespace in string