Recursive regex in python?

I have a line:

acd (e(fg)h) ij)

I need to remove the text in the open and corresponding closed bracket. So in the example I need to delete

(e(fg)h)

As a result, I want to have

acd del ij)

I am trying to use the following code:

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

But python says:

sre_constants.error: unexpected end of pattern
+4
source share
1 answer

Thanks Jerry and devnull! regex for python instead of the standard re module solved my problem

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

Source: https://habr.com/ru/post/1537281/


All Articles