Python regex to extract everything within brackets

Question:

I want to create Regex that is going to extract everything within brackets, but there is only one condition, if we have other pair of brackets inside, it should extract only what is inside. See example:

(something(1,2,3))

If we use regex on it, it should extract this:

something(1,2,3)

But if we have more complicated structure like this one:

something(1, test1(2,3), test2(3,4))

After using regex it should be:

1, test1(2,3), test2(3,4)

And after next use:

2,3
3,4

As far as I could get is next regex: (.*?)*$, but it doesn’t work how it is supposed to work. So, for example, if you use this regex on something(1, test1(2,3), test2(3,4)) for the first time you will get: (1, test1(2,3), test2(3,4)), and this is fine, but then, after deleting the first ( and last ), on the second you you will get: (2,3), test2(3,4).

I am not quite expert in Regex, so I am not sure why this is wrong and how I can fix that.

Thanks in advance.

Asked By: dokichan

||

Answers:

Regex recursion should help with this. /(([^()]|(?R))*)/g

https://regex101.com/r/CcXSGk/1

Answered By: Celin Jane
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.