We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Find and replace only the first word in document

I want to replace only the first word found. Is there any FindReplaceOption for that? I couldn’t find in the documentation.

@gkumar16 there is not an specific option for replace only the first occurrence, but you can easily implement it using the callback class that you are allowed to inject in the FindReplaceOptions. See the following code as example:

class ReplaceXTimes : IReplacingCallback
    public ReplaceXTimes(int replacementAmount)
        ReplacementAmount = replacementAmount;
        TrackCounter = 0;
    public ReplaceAction Replacing(ReplacingArgs args)
        if(TrackCounter < ReplacementAmount)
            return ReplaceAction.Replace;

        return ReplaceAction.Stop;

    private int TrackCounter;
    private readonly int ReplacementAmount;
doc.Range.Replace("ReplaceThisText", "ByThisText", new FindReplaceOptions(FindReplaceDirection.Forward, new ReplaceXTimes(1)));