Ivan Borshchov
Ivan Borshchov

Reputation: 3549

Recursive regexp in python?

I have string:

acd (e(fg)h) ij)

I need to delete text within opened and coresponding closed bracket. So in example I need to delete

(e(fg)h)

In result I want to have

acd del ij)

I try to use next code:

re.sub(r'\((((?>[^()]+)|(?R))*)\)', r'del', 'acd (e(fg)h) ij)')

But python say:

sre_constants.error: unexpected end of pattern

Upvotes: 5

Views: 3410

Answers (1)

Ivan Borshchov
Ivan Borshchov

Reputation: 3549

Thanks Jerry and devnull! regex module for python instead of default re module solved my issue

import regex
>>> regex.sub(r'\((((?>[^()]+)|(?R))*)\)', r'del', 'acd (e(fg)h) ij)')
'acd del ij)'

Upvotes: 4

Related Questions