Find and replace question

Hallo

I'm evaluating Aspose Words to create some custom reports based on Word templates.
What I need is:
1. Find all variables in the Word document template (e.g.. All texts between defined brackets, for example "$......$")
2. Replace the found variables with custom texts

I couldn't find the code snippet to do this, also in the samples I couldn't find anything.
In the sample you have samples which work with Bookmarks, but I don't want to use Bookmarks but real text tags.
Anyway in the samples there was no way to find out the Bookmarks (which need to be dynamic in my solution).

Thanks in advance
David Pizzi

Hey David,

You should use find and replace functionality.

To replace your custom tags with a constant string use the following method:

doc.Range.Replace(new Regex(@"\$\w+\$"), "Hello")

In case the replacement may vary depending on some condition, use replace evaluator:

public void TestReplace()

{

Document doc = TestUtil.Open("Source.doc");

doc.Range.Replace(new Regex(@"\$\w+\$"), new ReplaceEvaluator(ReplaceEvaluator), false);

TestUtil.SaveShow(doc, "Result.doc");

}

private ReplaceAction ReplaceEvaluator(object sender, ReplaceEvaluatorArgs args)

{

args.Replacement = "The string to replace based on some condition";

return ReplaceAction.Replace;

}