Reputation: 195
I have the following unwieldy code to extract out 'ABC' and '(XYZ)' from a string 'ABC(XYZ)'
import re
test_str = 'ABC(XYZ)'
partone = re.sub(r'\([^)]*\)', '', test_str)
parttwo_temp = re.match('.*\((.+)\)', test_str)
parttwo = '(' + parttwo_temp.group(1) + ')'
I was wondering if someone can think of a better regular expression to split up the string. Thanks.
Upvotes: 0
Views: 95
Reputation: 474191
For this kind of input data, we can replace the (
with space+(
and split by space:
>>> s = 'ABC(XYZ)'
>>> s.replace("(", " (").split()
['ABC', '(XYZ)']
This way we are artificially creating a delimiter before every opening parenthesis.
Upvotes: 0
Reputation: 174844
You may use re.findall
>>> import re
>>> test_str = 'ABC(XYZ)'
>>> re.findall(r'\([^()]*\)|[^()]+', test_str)
['ABC', '(XYZ)']
>>> [i for i in re.findall(r'(.*)(\([^()]*\))', test_str)[0]]
['ABC', '(XYZ)']
Upvotes: 1