Benjamin
Benjamin

Reputation: 280

How do I replace only specific match in a match collection?

I am writing a solve method that solves an equation. The method will be recursive; searching for all outer parenthesis and when found recall solve for values inside the parenthesis and return the value when no parenthesis are found.

The process should look like this

20 * (6+3) / ((4+6)*9)
20 * 9 / ((4+6)*9)
20 * 9 / (10*9)
20 * 9 / 90
2

As you see each match may have a different replacement value. I need to replace the parenthesis to what it evaluates to. Is there a way to do this. Here is what I have so far.

public int solve(string etq)
{
    Regex rgx = new Regex(@"\(([^()]|(?R))*\)");
    MatchCollection matches;

    matches = rgx.Matches(etq);
        
    foreach(Match m in matches)
    {
        //replace m in etq with unique value here
    }

    //calculations here
    return calculation
}

Regex.replace(...) replaces all occurrences of the pattern specified. I want to be able to match to multiple scenario and replace each scenario with different output

Upvotes: 2

Views: 3403

Answers (2)

bigtv
bigtv

Reputation: 2711

This would be an even simpler solution, using the match properties to replace using substring:

public static string Replace(this Match match, string source, string replacement) { return source.Substring(0, match.Index) + replacement + source.Substring(match.Index + match.Length); }

Upvotes: 2

Ulugbek Umirov
Ulugbek Umirov

Reputation: 12807

Simple solution:

string input = "20 * (6+3) / ((4+6)*9)";
Console.WriteLine(input);
DataTable dt = new DataTable();
Regex rx = new Regex(@"\([^()]*\)");
string expression = input;
while (rx.IsMatch(expression))
{
    expression = rx.Replace(expression, m => dt.Compute(m.Value, null).ToString(), 1);
    Console.WriteLine(expression);
}
Console.WriteLine(dt.Compute(expression, null));

https://dotnetfiddle.net/U6Hh1e

Upvotes: 8

Related Questions