As already mentioned by others: regex is not well suited for such a task. However, if your parenthesis do not exceed a fix number of nesting, you could do it, but if the nesting can be 3 or more, the regex will become a pain to write (and maintain!). Have a look at the regex that matches parenthesis with at most one nested parenthesis in it:
\((?:[^()]|\([^)]*\))*\)
which means:
\( # match the character '('
(?: # start non-capture group 1
[^()] # match any character not from the set {'(', ')'}
| # OR
\( # match the character '('
[^)]* # match any character not from the set {')'} and repeat it zero or more times
\) # match the character ')'
)* # end non-capture group 1 and repeat it zero or more times
\) # match the character ')'
The version for 3 will make your eyes bleed! You could go with .NET's feature of recursive regex matching, but I personally wouldn't go: sprinkling recursion inside regex leads to madness! (not really of course, but regex are hard enough to comprehend and mixing recursion to the mix, doesn't make it any clearer IMO)
I'd just write a small method that might look like this Python snippet:
def find_parens(str):
matches = []
parens = 0
start_index = -1
index = 0
for char in str:
if char == '(':
parens = parens+1
if start_index == -1:
start_index = index
if char == ')':
parens = parens-1
if parens == 0 and start_index > -1:
matches.append(str[start_index:index+1])
start_index = -1
index = index+1
return matches
for m in find_parens("dfgdgdfg (aaa.bbb) sfd (c) fdsdfg ( ,ddd (eee) )"):
print(m)
which prints:
(aaa.bbb)
(c)
( ,ddd (eee) )
I'm not familiar with C#, but the Python code above reads just like pseudo code and wouldn't take much effort to convert into C# I presume.