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