Find and replace for a non-unique word in a document

Currently creating a script to delete a specific instance of the word “Title” in a document. The problem is that the word “Title” appears all over the document so using Document.Range.Replace(“Title”, “”) will lead to many unwanted deletions. Is it possible to search for unique formatting when using Replace()? The word I wish to replace is the only instance of the word that is bold and italics. Coding in .Net using Visual Basic. Thank you for any ideas or help.

Hi @SethD02 ; can you show us the piece of code that you are trying to use. Also if you can explain the expected result that you want to accomplish. It seems that what you are trying to accomplish can be achieved, using something like:

FindReplaceOptions options = new FindReplaceOptions();
options.ReplacingCallback = myCallbackFunction;    

In your callback function you need to check the args for italic and then return the replace action. You can check the documentation here FindReplaceOptions.ReplacingCallback | Aspose.Words for .NET
Thanks :vulcan_salute::nerd_face:

1 Like

@SethD02 Yes, @BobRozas is absolutely right. You can achieve what you need using IReplacingCallback. Please see the following simple code example:

Document doc = new Document(@"C:\Temp\in.docx");
FindReplaceOptions opt = new FindReplaceOptions();
opt.ReplacingCallback = new MyReplacingCallabck();
doc.Range.Replace("Title", "", opt);
doc.Save(@"C:\Temp\out.docx");
private class MyReplacingCallabck : IReplacingCallback
{
    public ReplaceAction Replacing(ReplacingArgs args)
    {
        Run matchRun = args.MatchNode as Run;
        // Replace only bold and italic text.
        if (matchRun != null && matchRun.Font.Bold && matchRun.Font.Italic)
            return ReplaceAction.Replace;

        return ReplaceAction.Skip;
    }
}
1 Like

Thank you for your answer. This is very valuable knowledge for my job. I was able to accomplish my task through a different workaround that looked something like this:

DocumentBuilder.MoveToMergeField("Field that was right after my desired text to delete")
Dim current As Node = DocumentBuilder.CurrentParagraph.PreviousSibling
current.Remove()
1 Like

I appreciate both of your responses and am still very thankful for this knowledge as I’m sure it will come in handy for me later in my job. If you look at my response above you can see a workaround I used to achieve my desired result. Thank you!

1 Like