Regex - math with cycle

Viewed 58

How to count the amount of a match inside itself to skip some characters?

Example:

I have:

(a(b(c)))

If I run this regex: \(.+?\)

It will be return: (a(b(c)

But what I want is the ) that closes the loop, that is, the third.

I could just remove the ? From the regex but there is a problem:

Ex: \(.+\) to (a)(a(b(c))) return (a)(a(b(c)))

And what I want is for the group to return to me with the closed loop of (), that is, it should return 2 matchs to me:

match 1: (a) match 2: (a(b(c)))

What is the question of counting in the match? Well, what I thought was if there is any way to count how many ( passed to know how many ) one should skip, that is:

1   2   3   1 2 3
( a ( b ( c ) ) )

Does anyone have any idea how to do this just using regex?

1 Answers

If you need to use regex, please try the recursive regex (?R).
The implementation depends on the language so let me explain it with python.

#!/usr/bin/python

import regex

str ='(a)(a(b(c)))'

m = regex.findall(r'\((?:[^()]|(?R))+\)', str)
print(m)

Output:

['(a)', '(a(b(c)))']

Explanation of the regex pattern \((?:[^()]|(?R))+\):

  • The inner part (?:[^()]|(?R))+ matches:
    • one or more [^()] or (?R) where
      • [^()] matches any character other than parentheses.
      • (?R) represents the entire regex \((?:[^()]|(?R))+\) recursively.
Related