Regex Replace Problem

Hello,
We’ve got a problem replacing text in a document template. We are trying to replace text between square brackets and generally the following code works well -

foreach (DataRow dr in dtData.Rows)
{
    Regex regexp = new System.Text.RegularExpressions.Regex(@"\[" + ((string)dr["FieldName"]).ToUpper() + @"\]", RegexOptions.IgnoreCase);
    strReplacement = (string)dr["FieldValue"];
    doc.Range.Replace(regexp, new ReplaceEvaluator(ReplaceBookmarkAction), false);
}
ReplaceAction ReplaceBookmarkAction(object sender, ReplaceEvaluatorArgs e)
{
    Run run = (Run)e.MatchNode;
    run.Text = string.Empty;
    DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document);
    builder.MoveTo(run);
    builder.Write(strReplacement);
    return ReplaceAction.Skip;
}

However, every now and again the matched text does not correspond to the regular expression passed into the Replace method. For example a reg expression [LegalRightsApplyOption] is returning “2\tLegal rights apply\t\t\t[LegalRightsApply” as the MatchNode’s range text.
We’ve tried JoinRunsWithSameFormatting before running the replace but this does not help greatly. Could you offer any suggestions as to how to get this to work consistently. Unfortunately mail merges are not an option as there are too many templates already predefined to make this change to them all.
I’ve attached a template that is causing us problems for you to look at.
Many thanks,
Joe

Hi

Thanks for your inquiry. If you need just replace placeholder with actual text, you do not need ReplaceEvaluator. You can use code like the following:

Document doc = new Document(MyDir + "Document.doc");
doc.Range.Replace("sad", "bad", false, true);

Please see the following link for more information:
https://docs.aspose.com/words/net/find-and-replace/
Regarding text in matched node, all text in word document is represented by Runs. In your case Run contains matched text, however, it also might contain other text. Please see the following article for more information:
https://docs.aspose.com/words/net/find-and-replace/
Best regards.

The problem being with this is that we may have carriage returns etc in the replacement text which results in an error if we do it this way.

In this case, you should split matched run. Please see the second article I provided in my previous answer.

Best regards.

Many thanks for the help - combining the SplitRun function in that article with JoinRunsWithSameFormatting works perfectly. The quick response was much appreciated!!