How To replace first occurrence of Expression in doc

Document doc = new Document("bug123.docx");
doc.getRange().replace("Hashmat Ullah Khattak", "this is testing replace",true,false);
doc.save("out.docx");

Attached file consists of two segments

1: Hashmat Ullah Khattak

2:This is create By Hashmat Ulah Khattak

Now problem is that when i try to run above code to replace Hashmat Ullah Khattak With "this is testing replace ". the above code replace both matches but i want to replace first segments “Hashmat Ullah khattak” with “this is testing replace” and second segment remain same like original “This file is create By Hashmat Ulah Khattak”

Is it is possible in aspose word for java??.

please help me and also share sample code please.

Thanks in Advance.

Best Regards:Hashmat Ullah

Hi

We are implementing IReplacingCallback interface and it replaces all occurrences of the text. how we can skip its execution after first occurrence.

This message was posted using Email2Forum by Imran Rafique. (private)

can you share sample code for me?

Hi Hashmat,

Thanks for your inquiry. Please use the following code example to achieve your requirements. I suggest you please read following documentation links for your kind reference.
https://docs.aspose.com/words/java/find-and-replace/

Hope this helps you. Please let us know if you have any more queries.

Document doc = new Document(MyDir + "bug123.docx");
doc.getRange().replace(Pattern.compile("Hashmat Ullah Hashmat"), new ReplaceFirstOccourance("this is testing replace"), 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();
        mMatchNumber++;
        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());

            // This array is used to store all nodes of the match for further highlighting.
            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))
            {
                runs.add(currentNode);
                remainingLength = remainingLength - currentNode.getText().length();
                // Select the next Run node.
                // Have to loop because there could be other nodes such as BookmarkStart etc.
                do
                {
                    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);
                runs.add(currentNode);
            }
            DocumentBuilder builder = new DocumentBuilder((Document)e.getMatchNode().getDocument());
            builder.moveTo((Run)runs.get(0));
            builder.write(replaceText);
            for (Run run : (Iterable) runs){
                run.remove();
            }
        }

        return ReplaceAction.SKIP;
    }

    private Run splitRun(Run run, int position) throws Exception
    {
        Run afterRun = (Run)run.deepClone(true);
        afterRun.setText(run.getText().substring(position));
        run.setText(run.getText().substring((0), (0) + (position)));
        run.getParentNode().insertAfter(afterRun, run);
        return afterRun;
    }
}

Thanks a lot, the solution you have given is not working for me.

let me explain more my problem.

suppose we have two segments

  1. I am here

  2. I am here in office

now i just want to replace segment 1 (I am here) with replacement (test) and does not want to replace segment two (I am here in office), the api (aspose word for java) replace first segment with (test) and second with (test in office i do not want to replace i am here in office) . I want to replace exact match like(I am here) with (test) not to replace partial matching (I am here in office)…

Im Waiting for kind replace:

Thanks:

Best Regard:

Hashmat Ullah Khattak

Hi Hashmat,

Thanks for your inquiry. The code shared in my previous post works fine with bug123.docx. I have attached the output and input documents with this post for your kind reference.

If the problem still remains, please attach your input Word document for which you are facing the issue? I will investigate the issue on my side and provide you more information.