Richard Foo
Richard Foo

Reputation: 195

Python regular expression to extract the parenthesis

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

Answers (3)

alecxe
alecxe

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

Abhijeet Kasurde
Abhijeet Kasurde

Reputation: 4127

[i for i in re.split(r'(.*?)(\(.*?\))', test_str) if i]

Upvotes: 0

Avinash Raj
Avinash Raj

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

Related Questions