class StringFormattingParser(object):
    __matcher = re.compile(
        '(?<!%)%\\(([^)]+)\\)[-# +0-9.hlL]*[diouxXeEfFgGcrs]')

@classmethod
def getKeyNames(klass, formatString):
    return klass.__matcher.findall(formatString)
for value in ['%(a)s and %(b)s are friends.', '%%(nomatch)i', '%%',
    'Another %(matched)+4.5f%d%% example', '(%(should_match(but does not))s']:
    print(StringFormattingParser.getKeyNames(value))
How to get the names of the named variables from the python string