user1539348 user1539348 - 3 years ago 127
Python Question

How to find characters not in parentheses

Attempting to find all occurrences of characters

str = '%(example_1).40s-%(example-2)_-%(example3)s_'

so that output has all occurrences of '-' '_' not in parentheses

['-', '_', '-', '_']

Do not need to care about nested parentheses

Answer Source

The following will give you your output.:

>>> import re
>>> str = '%(example_1).40s-%(example-2)_-%(example3)s_'
>>> print list("".join(re.findall("[-_]+(?![^(]*\))", str)))
['-', '_', '-', '_']

What this does is it finds all the substrings containing '-' and/or '_' in str and not in parentheses. Since these are substrings, we get all such matching characters by joining, and splitting into a list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download