Replace with Only the First Word Found in Document using C#

Hi

How can I replace with only the first word found in my Word DOC document?

Hi

Thank you for your interest in Aspose products. I think that you can try using ReplaceEvaluator to achieve this. For example see the following code.

C# Code to Find & Replace a Keyword in Document

// Load Word DOC document from file system
Document doc = new Document("find and replace.doc");

// Use regular expression to match string in Word document
Regex regex = new Regex("some words");

// Specify options for find and replace operations
FindReplaceOptions options = new FindReplaceOptions();
options.Direction = FindReplaceDirection.Forward;
options.ReplacingCallback = new Find_Replace_Evaluator();

// Replace keyword with new string
doc.Range.Replace(regex, "new text to replace with", options);

// Save as to DOCX file
doc.Save("word.docx");

private class Find_Replace_Evaluator : IReplacingCallback
{
    int replaceCount = 0;

    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        // Replace only the first match and then Stop
        if (replaceCount == 0)
        {
            replaceCount++;
            return ReplaceAction.Replace;
        }
        else
        {
            return ReplaceAction.Stop;
        }
    }
}