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

Free Support Forum - aspose.com

Aspose Words - How to replace first?

Hi There,

I have a paragraph with the text:
One Two Three One Two One

I need replace the first “One”, How I can do it? The API only allows to replace using a pattern.

Any suggestion?

Thank you.


Hi Rui,

Thanks for your inquiry. Please use the following code example to achieve your requirements. We suggest you please read following articles. Hope this helps you.

Find and Replace Overview
How to Find and Highlight Text

Document doc = new Document(MyDir + “in.docx”);

doc.getRange().replace(Pattern.compile(“One”), new ReplaceFirstOccourance(“One is replaced”), true);

doc.save(MyDir + “Out.docx”);

public class ReplaceFirstOccourance implements IReplacingCallback


String replaceText = “”;

private int mMatchNumber = 0;

public ReplaceFirstOccourance(String text)


replaceText = text;


public int replacing(ReplacingArgs e) throws Exception {

// This is a Run node that contains either the beginning or the complete match.

Node currentNode = e.getMatchNode();


if(mMatchNumber == 1)


// The first (and may be the only) run can contain text before the match,

// in this case it is necessary to split the run.

if (e.getMatchOffset() > 0)

currentNode = splitRun((Run)currentNode, e.getMatchOffset());

ArrayList runs = new ArrayList();

// Find all runs that contain parts of the match string.

int remainingLength = e.getMatch().group().length();

while (

(remainingLength > 0) &&

(currentNode != null) &&

(currentNode.getText().length() <= remainingLength))



remainingLength = remainingLength - currentNode.getText().length();

// Select the next Run node.

// Have to loop because there could be other nodes such as BookmarkStart etc.



currentNode = currentNode.getNextSibling();


while ((currentNode != null) && (currentNode.getNodeType() != NodeType.RUN));


// Split the last run that contains the match if there is any text left.

if ((currentNode != null) && (remainingLength > 0))


splitRun((Run)currentNode, remainingLength);



DocumentBuilder builder = new DocumentBuilder((Document)e.getMatchNode().getDocument());



for (Run run : (Iterable) runs){




return ReplaceAction.SKIP;


private Run splitRun(Run run, int position) throws Exception


Run afterRun = (Run)run.deepClone(true);


run.setText(run.getText().substring((0), (0) + (position)));

run.getParentNode().insertAfter(afterRun, run);

return afterRun;