1

I want to match the following text:

(valuex) AnySingleWord (valuey)

I want to capture the text of valuex,valuey within the brackets. The tough thing is valuex,valuey both can contain brackets as well. For example

((value1) AnySingleWord (value2)) AnySingleWord ((value3) AnySingleWord (value4))

Then my valuex should be

(value1) AnySingleWord (value2) 

and valuey should be

(value3) AnySingleWord (value4)

Can regex do something like counting the number of open bracket has passed, and match things until the right close bracket found? many thanks.

PS: I can limit number of open/close bracket pairs to 2-3, if this is small enough to be solvable by Regex

Ben.Yan
  • 118
  • 4
  • 13

3 Answers3

2

Yes, you can use this pattern:

\(((?>\((?<DEPTH>)|\)(?<-DEPTH>)|[^()]+)*(?(DEPTH)(?!)))\)

more informations about this kind of pattern here:

http://blogs.msdn.com/b/bclteam/archive/2005/03/15/396452.aspx

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • This works, many thanks. Great as this is my individual work, otherwise teammate is gonna murder me, or I am gonna frustrating explain Regex balanced matching group. – Ben.Yan Jun 21 '13 at 20:56
1

A pretty simple way would be as follows if I'm understanding you correctly:

1. iterate through characters
2. find first left brace
3. count braces until non-paired right brace appears and store index
4. take the substring from zero to that index and set as value x
5. delete value x substring
6. go to step 1 and store next part as value y
eatonphil
  • 13,115
  • 27
  • 76
  • 133
  • 1
    this would be intuitive a non-regex solution, if i can't manage to handle using regex, i would try this – Ben.Yan Jun 20 '13 at 19:04
  • Sure! It would also be a lot easier to read and debug. It's your choice, but this scenario certainly seems to lend itself to a non-regex solution. – eatonphil Jun 20 '13 at 19:09
1

Your regex would be

(?<left>\(([^()]*(\([^()]*\))?[^()]*)+\))[^()]*(?<right>\([^()]*((\([^()]*\))?[^()]*)+\))

Your code would be

Match m=Regex.Match(inp,reg);
m.Groups["left"].Value;//left value
m.Groups["right"].Value;//rightvalue
Anirudha
  • 32,393
  • 7
  • 68
  • 89