Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Thu Jun 02, 2022 12:04 pm

I am looking for a placeholder and replace it with a text string. This works fine with findAllString and replace. The problem is that the replace does it over the entire document and I need to replace each placeholder found in the document with a different value, even though the name of the placeholder is the same. These placeholders can be in different paragraphs but they can also be in the same paragraph.

Example:
Test1 <<YYYY>>, Test2 <<YYYY>>, Test3 <<YYYY>>

In this example, my placeholder to search for is <<AAAA>>, but the value to put in its place must be different in each one.

Example of desired result:

Test1 11111, Test2 22222, Test3 33333

jmparada
 
Posts: 47
Joined: Wed May 25, 2022 7:50 am

Fri Jun 03, 2022 5:42 am

Hello,

Please refer to the following sample code to achieve your demand, if there is still any issues, please provide your word file for further investigation.
Code: Select all
        Document doc = new Document();
        doc.loadFromFile("in.docx");
        Pattern regex=Pattern.compile("\\<<[^\\d]+\\>>");
        TextSelection[] textSelections = doc.findAllPattern(regex, true);
        String[] replaceArray = {"1111", "2222","3333"};
        for (int i=0;i<textSelections.length;i++)
        {
            TextSelection text = textSelections[i];
            TextRange range = text.getAsOneRange();
            //set replace first
            doc.setReplaceFirst(true);
            doc.replace(range.getText(), replaceArray[i],false,true);
        }
        doc.saveToFile("out.docx", FileFormat.Docx_2013);

Sincerely,
Lisa
E-iceblue support team
User avatar

Lisa.Li
 
Posts: 1261
Joined: Wed Apr 25, 2018 3:20 am

Mon Jun 06, 2022 8:24 am

ok it works fine using setReplaceFirst. Thanks.

jmparada
 
Posts: 47
Joined: Wed May 25, 2022 7:50 am

Return to Spire.Doc