Take the 2-minute tour ×

Converting an old program into an ASP.NET c# site.

I have a table full of functions and a table full of variables with their corresponding values. I've written a function to evaluate the answers but need to format the formulas in order to pass the variable in.

For example:

V(totalValue) * V(CoFriction(s)) ==>  V("totalValue") * V("CoFriction(s)")

How can I replace the V(<variable>) to V("<variable>"). Nested parenthesis are possible!

I've tried regexp like - V\([^\(\)]+\) only to fail on the nested paren.

share|improve this question
Well, if nested parenthesis are allowed/possible, how would you determine when the value is a string literal and when it is not? What would it mean when a function that is to be treated as a string literal has another function as a parameter that must also be treated as a string literal? It sounds to me like you need to write a simple recursive descent parser that, as soon as it finds a function name that it knows about, starts bracket matching untill the closing bracket is found and surrounds the whole lot with inverted commas. Otherwise, you will have to evaluate named functions at run time. –  Kell Nov 1 '10 at 18:06

2 Answers 2

up vote 2 down vote accepted

You can achive it in .net using a balancing group:

string s = "V(totalValue) * V(CoFriction(s)) * V(a(()b)c()d((())))";

string vPattern =
(       #capturing group, for $1 to work
        (?<open>\()|    #push to stack OR
        (?<-open>\))|   #pop from stack OR
        [^()]           #match anything else
(?(open)(?!))   #assert there are not extra (

s = Regex.Replace(s, vPattern, "V(\"$1\")", RegexOptions.IgnorePatternWhitespace);

The regex works exactly for the posted scenarios - it will fail miserably if the input isn't valid, so you assume it is (specifically, when you have extra closing parentheses).

share|improve this answer
Thanks for your assistance. –  JibberSki Nov 1 '10 at 19:36
Wow, I have learned something new :) But yikes, I'm not sure I'll ever use this! –  Kell Nov 2 '10 at 10:06
@Kell - Thanks. This notation specific to .Net and beyond recreation has only limited used, but it is well suited for this case - it allows capturing balanced tokens, but not capturing each individual pair of parentheses. Of course, it isn't difficult to count the parentheses manually, which is a valid solution. –  Kobi Nov 2 '10 at 10:28

I've built libraries like this in the past. The Regex feature you want is called "balancing groups". There's a good writeup at http://blog.stevenlevithan.com/archives/balancing-groups I think you want something like this:

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

If I remember correctly this will essentially add a paren onto the "Depth" stack when it sees an open-paren, remove it from the "Depth" stack when it sees a close paren (if there is none on the stack it fails), and then fails of an open paren isn't closed.

share|improve this answer

Your Answer


