Complicated Search And Replace

I have a rather complicated requirement to find dynamic text within a document and replace it with calculated data. There is no finite list of what I am trying to replace, so I ma having to use regular expressions to locate the correct text. I need to know if there is a way to iterate through the document in order to insure that I can replace all of the instances of text. Here is an example of text that needs replacing:

There are [CARS:Total] cars on the lot. Of these [CARS:Blue] are blue cars and [CARS:Red] are red cars.

Will the following code work (assuming I have my regular expression correct)?

System.Text.RegularExpressions.Match expressionMatch = regex.Match(word.Range.Text);
if (expressionMatch.Success)
{
    word.Range.Replace(regex, GetValue(expressionMatch.Value));
}

Thanks in advance.

Don Pruitt

The above does not work. When I run it, it replaces all instances (Total, Red,Blue) with the value for Total.

Is there a way to replace each instance independently?

The following code seems to work ok:

private void ReplaceTest()
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.Writeln(@"There are [CARS:Total] cars on the lot. Of these [CARS:Blue] are blue cars and [CARS:Red] are red cars.");
    Regex regex = new Regex(@"\[CARS:.\*?\]");
    while (true)
    {
        Match match = regex.Match(doc.GetText());
        if (match.Success)
        {
            doc.Range.Replace(match.Value, GetValue(match.Value), false, false);
        }
        else
            break;
    }
    string filename = "TestResult.doc";
    doc.Save(filename);
    System.Diagnostics.Process.Start(filename);
}

private string GetValue(string matchText)
{
    switch (matchText)
    {
        case "[CARS:Total]":
            return "10";
        case "[CARS:Blue]":
            return "3";
        case "[CARS:Red]":
            return "1";
        default:
            return "-";
    }
}

Although the approach like this will be a bit slow. I would rather use range replacement with ReplaceEvaluator, which is described here:

https://docs.aspose.com/words/net/working-with-ranges/

Best regards,