Replace Error with bad spaces

Hi!

I’ve come across quite a strange error here.

With Replace I replaced some placeholders in a template. Since the format of many replacements in the real template is also adapted, I always do the replacements in an IReplacingCallback class. For the placeholders I determine all runs and delete them. This works very well in itself.

Now I have a template where the determination of the runs brings an error. Reason for it: In the text property of MatchNode there are two placeholders, the next time no placeholders. This leads to the error. The reason is the space between the placeholders. If I delete it in Word and insert it again, it works without errors.

Unfortunately, we have no influence on the templates of our customers and can therefore not ensure that no such spaces are included.

I can’t see any difference in the spaces in either Word or Visual Studio.

In the test project they can see the behavior well. WordsReplaceBadSpaces.zip (22.7 KB)

Can you help me here?

Many thanks!
Markus

@MarkusPlesoft,

Please try specifying FindReplaceOptions.Direction property to Backward. Hope, this helps.

Document doc = new Document("E:\\WordsReplaceBadSpaces\\Template1.dot"); //Brings Error
//Document doc = new Document("E:\\WordsReplaceBadSpaces\\Template2.dot"); //Runs
FindReplaceOptions options = new FindReplaceOptions()
{
    Direction = FindReplaceDirection.Backward,
    PreserveMetaCharacters = true,
    ReplacingCallback = new FindAndReplace()
};
doc.Range.Replace(new Regex("<.+?>"), "", options);
doc.Save("E:\\WordsReplaceBadSpaces\\19.9.docx");