Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top