I want to replace only the first word found. Is there any FindReplaceOption for that? I couldn’t find in the documentation.
Thanks
@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)
{
TrackCounter++;
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)));
@eduardo.canal
This is my FindAndReplaceOptions
FindReplaceOptions findReplaceOptions = new FindReplaceOptions();
findReplaceOptions.setDirection(FindReplaceDirection.FORWARD);
findReplaceOptions.setMatchCase(true);
findReplaceOptions.setFindWholeWordsOnly(true);
findReplaceOptions.setReplacingCallback(new ReplaceXTimes(1));
The callback is getting triggered even for the matches that doesn’t satisfy the above conditions like FindWholeWordsOnly. Is that expected?