Free Support Forum - aspose.com

Find text with regex and replace with merge field

Hi,

I am evaluating whether Aspose can fix my problem. I have hundreds of word documents. In each document, there is a date written as a simple string/text. As such

Subject to the terms, conditions, limitations, exclusions and cancellation provisions of the relative contract number(s), as held on file by XXX effective for the period from 31st July, 2020 to 24.00 hours, 31st July, 2021, Local Standard Time, Sao Paolo, Brazil.

I need to 1) find this date using regex, and 2) replace it with a merge field and save the doc.

I am using this regex:
(?<=period from\s)(\d{1,2}\w{0,2}\s\w*,?\s\d{4})

The approach I am currently trying is to use:
document.getRange().replace(myRegexPattern, “”, options);

in “options” I pass a callback. In the call back, I

  • create a documentBuilder
  • builder.moveTo(e.getMatchNode())
  • builder.insertField(String.format(" MERGEFIELD %s ", _mergeFieldName));

However the e.getMatchNode does not always lead me to the right location in the document. Sometime my merge field is inserted in the right place, sometime a few words too early in the doc.

Do I need to build some logic using e.getMatchNode and e.getMatchOffset? Or is there a simpler way?

Thank you,

Yes, you are using the correct approach to find the text and replace it with merge field.

In your case, we suggest you please check the code example shared in the following article. The code example finds the text and highlight it.

How to Find and Highlight Text

In the code example, you need to replace your code with following code snippet.

// Now highlight all runs in the sequence.
for (Run run : (Iterable<Run>) runs)
    run.getFont().setHighlightColor(Color.YELLOW);

Please make sure that you are using the correct Regex according to your requirement.